censor word from text file and create new file - python

using python to censor the word "winter" from user input file - "y.txt"
wrote some code but i'm running into errors. any occurrence of the word "winter" should be gone. help and thanks!
filename = input("Enter file name (without extension): ")
file1 = filename+".txt"
file2 = filename+"_censored.txt"
word = input("Enter the word you are searching for: ")
#In this case, the input would be "winter"
print("\nLooping through the file, line by line.")
in_text_file = open(file1, "r")
out_text_file = open(file2,"w")
for line in in_text_file:
print(line)
out_text_file.write(line)
n = [ ]
def censor(word, filename):
for i in text.split(""):
if i == word:
i = "*" * len(word)
n.append(i)
else:
n.append(i)
return "".join(n)
censor(word,filename)
in_text_file.close()
out_text_file.close()
im getting the errors

the word winter is not quoted: censor(winter,filename) should be censor("winter",filename) or censor(word, filename)
Edit: also you need to open the file and read a line into the text variable.
Personally, I would use regular expressions to avoid gotchas with periods.
import re
then for each line:
line = re.sub(r'(^| )word here($| |\.|,|\;)','*****',line);

Related

Is there a way to output a link to a file with Python?

I have some code to sort a text and output info on it.
How it works is you copy a text a paste it into a text(.txt) file and save the file where the python file is saved. Then you go into the command prompt and type python3 the_name_of_the_python_file.py the_name_of_the_text_file.txt. When you run it, it outputs "All counted!". After that you have a new .txt file where the python file is saved and it tells you the number of words and unique words in the text file you attached. The new file will also list out what words are the most to least used.
Is there a way to get my code to output "All counted!" and then a link like thing that I can click on to open the new file?
Here is my code:
import sys
text_file = open(sys.argv[1], "r")
word_list = text_file.read().split(",")
word_list = "".join(word_list)
word_list = word_list.split(".")
word_list = "".join(word_list)
word_list = word_list.split(" ")
file_name = []
file_name = sys.argv[1].split(".")
text_file.close()
NumWords = 0
NumUniqueWords = 0
Words = {}
for i in word_list:
if i not in Words.keys():
NumWords += 1
NumUniqueWords += 1
Words[i.lower()] = 1
else:
NumWords += 1
Words[i] += 1
def get_key(val):
for key, value in Words.items():
if value == val:
return key
newfile = open(file_name[0] + "-count.txt", "w")
newfile.write("Total Words - {}\nUnique Words - {}\n\n".format(NumWords, NumUniqueWords))
for i in range(len(Words)):
newfile.write("{} - {}\n".format(get_key(max(Words.values())), max(Words.values())))
del(Words[get_key(max(Words.values()))])
newfile.close()
print("All counted!")
I do have things in my code to eliminate ","'s and "."'s and the same word capitalized or lowercase.

Open text file and slice words based on blank spaces

I want to open text file and slice words based on blank spaces, but cut by \n. Why does it work like this? Is the problem in the text file or that my code is wrong?
def process(w):
output =""
for ch in w:
if ch.isalpha() :
output += ch
return output.lower()
words = set()
fname = input("file name: ")
file = open(fname, "r")
for line in file:
lineWords = line.split()
for word in lineWords:
words.add(process(lineWords))
print("Number of words used =", len(words))
print(words)
Text file:
Result:

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")

How to iterate through a file once a word is found

I am searching a text file for an input word. However, I am only meant to search the text in the file after the word "START". The first twenty-odd before "START" should be ignored. I know how to find "START", but not how to search the rest of the file once "START" is encountered. I would appreciate any guidance!
Here is what I have so far:
file = open("EnglishWords.txt", "r")
print("***** Anagram Finder *****")
word = input("Enter a word: ")
for line in file:
if "START" in line:
if word in line:
print("Yes, ", word, " is in the file.", sep="")
else:
print("Sorry, ", word, " is not in the file.", sep="")
file.close()
Here is a sample of the text file:
The name of Princeton University or Princeton may not be
used in advertising or publicity pertaining to
distribution of the software and/or database. Title to
copyright in this software, database and any associated
documentation shall at all times remain with Princeton
University and LICENSEE agrees to preserve same.
START
clobber
transversalis
squinter
cunner
damson
extrovertive
absorptive
Modifying your code, we have
file = open("EnglishWords.txt", "r")
print("***** Anagram Finder *****")
word = input("Enter a word: ")
start_looking = False
word_found = False
for line in file:
if not start_looking:
if "START" in line:
start_looking = True
else:
continue
if word in line:
print("Yes, ", word, " is in the file.", sep="")
word_found = True
break
if not word_found:
print("Sorry, ", word, " is not in the file.", sep="")
file.close()
As long as START hasn't been found, keep skipping over the lines of the file. If, however, you encounter START, reset your flag and begin looking.
Do a for after your word is found:
with open(myfile, 'r') as f:
for line in f:
if 'START' in line:
# do stuff to lines below 'START'
# you could do another for loop here to iterate
for line in f:
print (line) # just an example
Very similar to this other SO post. Credit for the syntax of my answer comes from its answer.
What about something with regex module ?
re.findall(r"START.*(word_to_search).*", entire_text)
This should return you the result only if there is a START before the word to search for. I hope that's what you're looking for.
EDIT :
For a solution line by line i would go with something like :
start_search = 0
with open(bigfile, "r") as f:
for line in f:
if "START" IN line:
start_search = 1
if start_search and word_to_search in line:
print("result foun")
return (word_to_search)
What about this ?
Keep it short, simple and explicit:
with open("EnglishWords.txt", 'r') as fin:
output = fin.readlines()
# Find the line that contains START
index = output.index("START")
# Search all the lines after that
for line in output[index+1:]:
if word in line:
print("Yes, ", word, " is in the file.", sep="")
else:
print("Sorry, ", word, " is not in the file.", sep="")
You could use Python's dropwhile() to locate the start of the words and iterate from there:
from itertools import dropwhile
print("***** Anagram Finder *****")
word = input("Enter a word: ").lower() + '\n'
with open("EnglishWords.txt") as f_words:
if word in dropwhile(lambda r: not r.startswith("START"), f_words):
print("Yes, {} is in the file".format(word.strip()))
else:
print("Sorry, {} is not in the file.".format(word.strip()))
You can use a boolean :
file = open(“testfile.txt”, “r”)
foundStart = False
for line in file:
if foundStart:
# do something...
elif line == "START":
foundStart = True

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