Editing a text file, then displaying it - python

In my code, I want to insert words into a text file from a user. So I have these words in the text file that must be replaced by the user input, here are the strings must be replaced in the file , adjective,plural_noun,noun.
file1 = open('Sample.txt', 'w')
*adjective*,*plural_noun*,*noun*,*verb*,*male_first_name* = [
line.strip() for line in open('Sample.txt')]
for t in *adjective* :
print(input("enter an adjective: ", file=file1))
print(input("enter an plural noun: ", file=file1))
print(input("enter an verb: ", file=file1))
file1.close()

A little something to get you started...
file1 = open('Sample.txt', 'r')
text = file1.read()
while (text.find('*replace*') != -1):
inp = raw_input("enter some text to replace: ");
text = text.replace('*replace*', inp, 1)
print(text)
If Sample.txt contains This is some text to *replace* and the user input is xyz, this code prints:
This is some text to xyz
Let's step through it bit by bit:
file1 = open('Sample.txt', 'r') opens the file for reading ('r' means "for reading").
text = file1.read() reads the content of the file and puts it in the variable text.
while (text.find('*replace*') != -1): looks for occurrences of the string *replace* and continues with the indented commands as long as it finds one.
inp = raw_input("enter some text to replace: "), which only runs if there is a remaining occurrence of *replace*, gets user input and puts it in the variable inp.
text = text.replace('*replace*', inp, 1), which also only runs if there is a remaining occurrence of *replace*, replaces the next occurrence of *replace* with the user input, overwriting the old text.
print(text), which runs once all occurrences of *replace* have been replaced with user input, prints out the new text.
This is not how you would write an efficient programme with lots of different *string* strings, but hopefully it will lead you in the right direction and walking before running is often a good idea.
There is excellent online Python documentation and you can also use the pydoc tool -- e.g. pydoc str.replace from the command line.

Related

How to get rid of the last whitespace when printing with end=" "?

Task:
Create a solution that accepts an input identifying the name of a text file, for example, "WordTextFile1.txt". Each text file contains three rows with one word per row. Using the open() function and write() and read() methods, interact with the input text file to write a new sentence string composed of the three existing words to the end of the file contents on a new line. Output the new file contents.
The solution output should be in the format
cat
chases
dog
cat chases dog
the "WordTextFile1.txt" has only 3 words each in a different row
cat
chases
dog
This is what I have which works however the last line with the sentence has an extra whitespace which is breaking my program. What can I do to get rid of the whitespace and fix my code? help!
file = input()
with open(file, "r+") as f:
list_words = f.readlines()
for word in list_words:
print(word.strip())
for word in list_words:
print(word.strip(), end = " ")
this is current output:
student
reads
book
student reads book(extra whitespace)
You are properly removing the last white space by word.strip() but adding end = " " just adds the last whitespace again. Change it to:
file = input()
with open(file, "r+") as f:
list_words = f.readlines()
# I don't see any reason having this for loop
# for word in list_words:
# print(word.strip())
print(' '.join(word.strip() for word in list_words) # this should work
Edit: Removed the list as it was not required. Thanks to #PranavHosangadi

Print character amount to the file Python

My code pretty much asks user input and a pre made text which it prints to the .txt file. I want to add the character calculator to print into the file, not as a print. Is it possible?
input = input(str("Type something: "))
file = open("harjoitus.txt", "w")
file.write(str("This code is here automatically.\n"))
file.write(str(input))
file.write(str("\n",))
file.close()
with open("harjoitus.txt", 'r') as file:
text = file.read().strip().split()
len_chars = sum(len(word) for word in text)
print(len_chars)
This pretty much prints the amount of characters as print not to the text file how I want it. Is it possible to edit this somehow that it prints the character amount straight to the file and not as a print?
First before you go into this appending, take a look at how many places you are calling str() its unnecessary most of these values are already stings and ready to be written. Also avoid variable names like input that have preassigned purposes in python. But to add this count to the end, collections.Counter is an option, you should open the file as a append. Then you can add this number to the end of your file.
from collections import Counter
user = input("Type something: ")
with open('harjoitus.txt', 'w') as f:
f.write("This code is here automatically.\n")
f.write(user)
f.write("\n")
with open('harjoitus.txt', 'r') as f:
content = f.read()
c = Counter(content)
tot = sum(c.values())
with open('harjoitus.txt', 'a') as f:
f.write(str(tot))
chrx#chrx:~/python/stackoverflow/10.11$ python3.7 stack.py
Type something: vash
chrx#chrx:~/python/stackoverflow/10.11$ cat harjoitus.txt
This code is here automatically.
vash
38

Can't import data from files into one line

I'm currently making this program that was given to me by my school and it's to write your own name in ASCII text art but that was just copying and pasting. I am trying to make it so the user enters an input and there their name is output. My program currently works except it doesnt stay on one line.
My code:
name = input("What is your name: ")
splitname = list(name)
for i in range(len(splitname)):
f=open(splitname[i] + ".txt","r")
contents = f.read()
print(contents)
And this is what it outputs:
I would like to get it all onto one line if possible, how would I do so?
The solution is a bit more complicated because you have to print out line by line, but you already need all the contents of the 'letter' files.
The solution would be to read the first line of the first letter, then concatenate this string with the first line of the next letter and so on. Then do the same for the second line until you printed all lines.
I will not provide a complete solution, but I can help to fix your code. To start you have to only read one line of the letter file. You can do this with f.readline() instead of f.read() each consecutive call of this function will read the next line in this file, if the handle is still open.
To print the ASCII letters one next to the other, you have to split the letter into multiple lines and concatenate all the corresponding lines.
Assuming your ASCII text is made of 8 lines:
name = input("What is your name: ")
splitname = list(name)
# Put the right number of lines of the ASCII letter
letter_height = 8
# This will contain the new lines
# obtained concatenating the lines
# of the single letters
complete_lines = [""] * letter_height
for i in range(len(splitname)):
f = open(splitname[i] + ".txt","r")
contents = f.read()
# Split the letter in lines
lines = contents.splitlines()
# Concatenate the lines
for j in range(letter_height):
complete_lines[j] = complete_lines[j] + " " + lines[j]
# Print all the lines
for j in range(letter_height):
print(complete_lines[j])

python prog which accept paragraph and scramle all the words in it

I have tried randomint .This is used to read a paragraph in from a file and then write the output to a file. I have code , but need help because it is not working quite as it should. Punctuation also needs to remain untouched. Need it completed by tomorrow
is there anyone who can help me out??
import random
print("This program reads text from a file, then scrambles the letters within each word, except for the first and last letter.")
print("It then writes the scrambled words to a file of your choice.")
file_str = input("Please enter a file name that you would like scrambled: ")
def scramble():
#prompt for user input file name
input_file = open(file_str)
#for each line in the file, split the words
for line in input_file:
words = line.split()
#only take middle letters, leaving first and last letter
word = list(words[1:-1])
#scramble words
r = random.randint(1, len(word)-1)
output.append(word[-1])
#scrambled word = first letter + scrambled + last letter
scrambled = word[0] + " ".join(output)
print(scrambled)
input_file.close()
output_file_str = input("Which file would you like to write this to?: ")
output_file = open(output_file_str, 'a+')
output_file.write(scrambled)
output_file.close()
print("Thank you. Your scrambled text has been written to the file. Goodbye.")
scramble()
output_file_str = input("Which file would you like to write this to?: ")
output_file = open(output_file_str, 'a+')
output_file.write(scrambled)
output_file.close()
print("Thank you. Your scrambled text has been written to the file. Goodbye.")
scramble()
Since you only want to modify word characters (leaving punctuation in place), I'd suggest reading the whole text of your file at once and using using regular expressions to match the words. The re.sub function can replace each matched word with a scrambled version:
import random
import re
def scramble_word(word):
if len(word) <= 3: # short words don't have enough letters to shuffle
return word
first, *middle, last = word # fancy unpacking! middle will be a list
random.shuffle(middle) # this modifies the list in place
return first + "".join(middle) + last # rejoin into a single string
def scramble_text(text):
return re.sub(r"\w+", lambda match: scramble_word(match.group()), text)
def scramble_file(input_filename, output_filename):
with open(input_filename) as input_file:
text = input_file.read()
scrambled_text = scramble_text(text)
with open(output_filename, "w") as output_file:
output_file.write(scrambled_text)
I'll leave it up to you to figure out how best to call scramble_file with the filenames you get by asking the user.

How do I search for text within a tab delimited file and print this information?

I need to search for something in a tab delimited text file. The user is supposed to input both the file and the thing that needs searching for. The programme is then supposed to return the whole line that the user inputted word is in. I have got two models so far because I've been coming at this problem from different angles. The first programme goes as follows:
import csv
searchfile = raw_input ('Which file do you want to search? ')
try:
input_file = open (searchfile, 'rU')
except:
print "Invalid file. Please enter a correct file"
csv_file_object = csv.reader(open(searchfile, 'rb'))
header = csv_file_object.next()
data=[]
for row in csv_file_object:
data.append(row)
searchA = raw_input ('which author?')
author_search = data[0::,0] == searchA
if author_search in searchfile:
print author_search
The problem with the first programme is that this error pops up:
TypeError: list indices must be integers, not tuple
I therefore attempted this method:
import csv
searchfile = raw_input ('Which file do you want to search? ')
try:
input_file = open (searchfile, 'rU')
except:
print "Invalid file. Please enter a correct file"
with open(searchfile) as f:
reader = csv.reader(f, delimiter="\t")
d = list(reader)
searchtype = raw_input ('Search on author or journal/conference or [Q = quit]')
if searchtype == 'author':
searchdataA = raw_input ("Input author name")
if searchdataA in input_file:
print line
elif searchtype == 'journal' or 'conference' or 'journal/conference':
searchdataJ = raw_input ("input journal/conference name")
if searchdataJ in d:
print line
elif searchtype == 'Q':
print "Program left"
else:
print "please choose either author or journal/conference"
This is unable to get beyond inputting the search parameters.
Any help on where to go with either programme would be much appreciated, or if I'm completely on the wrong track then links to useful material would be great.
I think you're making this a bit more complicated than it needs to be. Since you want to print the whole line that the target word appeared on, you don't really need the CSV module. You're not doing any of the sophisticated parsing it is capable of.
searchfile = raw_input ('Which file do you want to search? ')
searchA = raw_input ('which author?')
with open(searchfile) as infile:
for line in infile:
if searchA in line:
print(' '.join(line.split()))
break # remove this if you want to print all matches instead of
# just the first one
Notice that in the when printing the line, I first split the line (which splits on whitespace by default), then rejoin the fields with two spaces between them. I think doing something like this would be a good way to go for you since you're printing tab-separated fields on the console. Reducing that extra space will make your prints a bit easier to read, but using two spaces still makes it easy to distinguish the columns from each other.
You can generalize it by prompting your user for any search term, instead of specifying "author". This may be the way to go, since your second code snippet suggests that you may want to search for other fields, like "journal" or "conference":
target_term = raw_input("Which term or phrase would you like to find?")
Since this method searches in and prints the entire line, there's no need to deal with the separate columns and different kinds of search terms. It just looks at the whole row at once and prints a matching line.
Since you are not really using a different search method, depending on if you are searching for author, journal, conference or journal/conference. So you could actually do a full text search on the line. Therefore it is wise to collect all data you need from user BEFORE processing file, so you can output just the matching lines. If user passes a rather large CSV file, then your way would take up far too much memory.
with open(searchfile, 'r') as f:
for line in f:
if line.find(searchA) > -1:
print line
This way you are looping through the file as fast as possible and prints out all matching lines.
The .find() function returns the index to where in the string he found the match and otherwise -1 if the string was not found. So from the value you could "estimate" on where the match was made, but if you really want to differentiate between author, journal, etc. then you will have to split the line. In my sample i will assume the author field to be the sixth field in the CSV line:
with open(searchfile, 'r') as f:
for line in f:
fields = line.split("\t")
if len(fields) > 5: # check length of fields array
if fields[5].find(searchA) > -1: # search straight in author field
print line # return full line
why not simply
fname = raw_input("Enter Filename")
author = raw_input("Enter Author Name:")
if author in open(fname,"rb").read():
print "match found"
if you want to see the lines you could do
print re.findall(".*%s.*"%(author),open(fname,"rb").read())
as people point out it is better form to do
with open(fname,"rb") as f:
data = print re.findall(".*%s.*"%(author),f.read())
although in CPython it will be garbage collected immediatly so its not really a problem....
The first thing that came to my mind is simply:
def check_file(file_name, author_name):
with open(file_name) as f:
content = f.readlines()
for line in content:
if author_name in line:
print "Found: ", line
Hope it can be useful.

Categories