Comparing text file content - python

I have written a small script to compare a text files content to another text file containing a word list, however running it says that the matches cannot be found, I cannot fix the code to successfully compare them with correct results.
wordlist = input("What is your word list called?")
f = open(wordlist)
t = f.readlines()
l = ''.join(t).lower()
chatlog = input("What is your chat log called?")
with open(chatlog) as f:
found = False
for line in f:
line = line.lower()
if l in line:
print(line)
found = True
if not found:
print("not here")

wordlist = input("What is your word list called?")
f = open(wordlist)
l = set(w.strip().lower() for w in f)
chatlog = input("What is your chat log called?")
with open(chatlog) as f:
found = False
for line in f:
line = line.lower()
if any(w in line for w in l):
print(line)
found = True
if not found:
print("not here")

Related

How can I delete a specific line from a txt file based on user input?

How do I go about deleting a specific line in a text file that is based on the user input?
def remove():
delete_value = input("Enter the value you wish to delete: ")
with open("values.txt", "r") as f:
lines = f.readlines()
with open("values.txt", "w") as f:
for line in lines:
if line.strip("\n") != delete_animal:
f.write(line)
Any help is appreciated, thank you!
Try this -
def remove():
num = []
delete_animal = input("Enter the name of the animal you wish to delete: ")
file = open("txt file", "r")
file.seek(0)
list_of_lines = file.readlines()
file.seek(0)
lines = file.read().splitlines()
file.close()
if delete_animal not in lines:
print("That line does not exist, please try again")
for word in lines:
num.append(0)
if delete_animal == word:
file = open('txt file','w')
list_of_lines[len(num)-1] = ""
file.writelines(list_of_lines)
print('Animal Deleted')
This should delete the line in which the input animal is there
EDIT-
It should be A3_s3902169_stock.txt. You need to add that extension .txt
def remove():
delete_value = input("Enter the value you wish to delete: ")
with open("value.txt", "r") as f:
file = f.readlines()
with open("value.txt", "w") as f:
for line in file:
# we will skip the line that contains our target word
# in this case the delete_animal
words = line.strip("\n").lower().split(' ')
if delete_value.lower() not in words:
f.write(line)
Input file:
line 1
line 2
line 3
line 4
may name is sudipto
my name is sudiptoandiloveprogramming
user input: sudipto
Output file after delete:
line 1
line 2
line 3
line 4
my name is sudiptoandiloveprogramming

Words Search in a txt document, python

I have this simple code that reads a txt file and accepts a word from the user to check if that word is in the txt document or not. It looks like this works only for a single word. I have to modify this code so that the user can input two or more words. Example; GOING HOME instead of just HOME. Any help please.
word = input('Enter any word that you want to find in text File :')
f = open("AM30.EB","r")
if word in f.read().split():
print('Word Found in Text File')
else:
print('Word not found in Text File')
I'm not sure this is exactly what you are looking for
f = open("AM30.EB","r")
word_list = []
while True:
word = input('Enter any word that you want to find in text File or 1 to stop entering words :')
if word == "1": break
word_list.append(word)
file_list = f.read().split()
for word in word_list:
if word in file_list:
print("Found word - {}".format(word))
These are case-sensitive solutions!
All words in query separately:
words = input('Enter all words that you want to find in text File: ').split()
f_data = []
with open("AM30.EB", "r") as f:
f_data = f.read().split()
results = list(map(lambda x: any([y == x for y in f_data]), words))
print("Found ")
for i in range(len(words)):
print(f"'{words[i]}'", end="")
if i < len(words) - 1:
print("and", end="")
print(f": {all(results)}")
Any word in query:
words = input('Enter any word that you want to find in the text File: ').split()
f_data = []
with open("AM30.EB", "r") as f:
f_data = f.read().split()
results = list(map(lambda x: any([y == x for y in f_data]), words))
if any(results):
for i in range(len(words)):
print(f"Found '{words[i]}': {results[i]}")
Exact phrase in query:
phrase = input('Enter a phrase that you want to find in the text File: ')
f_data = ""
with open("AM30.EB", "r") as f:
f_data = f.read()
print(f"Found '{phrase}': {f_data.count(phrase) > 0}")
This is case sensitive and checks for each word individually. Not sure if this is what you were looking for but hope it helps!
file1 = open('file.txt', 'r').read().split()
wordsFoundList = []
userInput = input('Enter any word or words that you want to find in text File :').split()
for word in userInput:
if word in file1:
wordsFoundList.append(word)
if len(wordsFoundList) == 0:
print("No words found in text file")
else:
print("These words were found in text file: " + str(wordsFoundList))

How to handle text file in python

I have a file name called words.txt having Dictionary words in it. I call this file and ask the user to enter a word. Then try to find out whether this word is present in this file or not if yes print True else Word not found.
wordByuser = input("Type a Word:")
file = open('words.txt', 'r')
if wordByuser in file: #or if wordByuser==file:
print("true")
else:
print("No word found")
The words.txt files contain each letter in a single line and then the new letter on the second line.
Use this one line solution:
lines = file.read().splitlines()
if wordByuser in lines:
....
Read the file first, also use snake_case https://www.python.org/dev/peps/pep-0008/
user_word = input("Type a Word:")
with open('words.txt') as f:
content = f.read()
if user_word in content:
print(True)
else:
print('Word not found')
This function should do it:
def searchWord(wordtofind):
with open('words.txt', 'r') as words:
for word in words:
if wordtofind == word.strip():
return True
return False
You just need to add .read() to the file class you initiated.
Like this:
wordByuser = input("Type a Word:")
file = open('words.txt', 'r')
data = file.read()
if wordByuser in data:
print("true")
else:
print("No word found")

Reading and Printing multiple files into one outfile

When reading and printing through my files, printing through my cousole gives me the correct result, but writing to the outfile does not
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
print(new_line)
This prints out all of the letters that I inputted
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
outfile.write(new_line)
It only gives me the last letter of the word inputted.
folder = r"C:\Users\sarah\Documents\a CPS 111\Bonus PA\stars\stars"
# os.listdir(folder) returns a list of files in folder
file_list = os.listdir(folder)
letter_art = {}
word = str(input("Please input a letter: "))
word = word.upper()
for fname in file_list:
letter_extension_list = fname.split(".")
for letter in word:
key = letter
value = letter_extension_list[1]
value = "%s."%(key) + value
letter_art[key] = value
fname = "\\".join([folder, value])
infile = open(fname, "r")
outfile = open("word_art.txt", "w")
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
print(new_line)
outfile.write(new_line)
infile.close()
outfile.close()
This is the code I am currently working with. I am taking in symbols from a txt file and changing them to the coornading letter depending on what the user inputed
Open the output file before the loop instead of within it:
outfile = open("word_art.txt", "w")
for letter in word:
with open("test.txt",'r') as f :
lines = f.readlines()
with open('out.txt','w') as outfile:
for line in lines:
new_line = line.replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
outfile.write(new_line)
This worked for me.
EDIT:
TigerhawkT3 is correct. I checked out your full code and you were opening the file again and again inside the loop, each time discarding the prior changes.

Replace four letter word in python

I am trying to write a program that opens a text document and replaces all four letter words with **. I have been messing around with this program for multiple hours now. I can not seem to get anywhere. I was hoping someone would be able to help me out with this one. Here is what I have so far. Help is greatly appreciated!
def censor():
filename = input("Enter name of file: ")
file = open(filename, 'r')
file1 = open(filename, 'w')
for element in file:
words = element.split()
if len(words) == 4:
file1 = element.replace(words, "xxxx")
alist.append(bob)
print (file)
file.close()
here is revised verison, i don't know if this is much better
def censor():
filename = input("Enter name of file: ")
file = open(filename, 'r')
file1 = open(filename, 'w')
i = 0
for element in file:
words = element.split()
for i in range(len(words)):
if len(words[i]) == 4:
file1 = element.replace(i, "xxxx")
i = i+1
file.close()
for element in file:
words = element.split()
for word in words:
if len(word) == 4:
etc etc
Here's why:
say the first line in your file is 'hello, my name is john'
then for the first iteration of the loop: element = 'hello, my name is john'
and words = ['hello,','my','name','is','john']
You need to check what is inside each word thus for word in words
Also it might be worth noting that in your current method you do not pay any attention to punctuation. Note the first word in words above...
To get rid of punctuation rather say:
import string
blah blah blah ...
for word in words:
cleaned_word = word.strip(string.punctuation)
if len(cleaned_word) == 4:
etc etc
Here is a hint: len(words) returns the number of words on the current line, not the length of any particular word. You need to add code that would look at every word on your line and decide whether it needs to be replaced.
Also, if the file is more complicated than a simple list of words (for example, if it contains punctuation characters that need to be preserved), it might be worth using a regular expression to do the job.
It can be something like this:
def censor():
filename = input("Enter name of file: ")
with open(filename, 'r') as f:
lines = f.readlines()
newLines = []
for line in lines:
words = line.split()
for i, word in enumerate(words):
if len(word) == 4:
words[i] == '**'
newLines.append(' '.join(words))
with open(filename, 'w') as f:
for line in newLines:
f.write(line + '\n')
def censor(filename):
"""Takes a file and writes it into file censored.txt with every 4-letterword replaced by xxxx"""
infile = open(filename)
content = infile.read()
infile.close()
outfile = open('censored.txt', 'w')
table = content.maketrans('.,;:!?', ' ')
noPunc = content.translate(table) #replace all punctuation marks with blanks, so they won't tie two words together
wordList = noPunc.split(' ')
for word in wordList:
if '\n' in word:
count = word.count('\n')
wordLen = len(word)-count
else:
wordLen = len(word)
if wordLen == 4:
censoredWord = word.replace(word, 'xxxx ')
outfile.write(censoredWord)
else:
outfile.write(word + ' ')
outfile.close()

Categories