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()
You need replace the letter
w
inw+
on line 4:file1 = open(filename, 'w')
haves to befile1 = open(filename, 'w+')
(I was working on this project too so this was my code)It can be something like this:
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.
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'
andwords = ['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: