November 8th, 2012, 05:37 PM
Opening text file, converting one four letter word to another
I am trying to open a saved text file that has a short sentence in it and then convert all four letter words in the sentence to "XXXX". Then save it back to the file. So far I am struggling with this. I pasted what I have done so far, but seem to be stuck now. I'm not sure what is wrong with what I have or if I am just missing something. Also I am new to the forum so if someone can tell me how to post my program properly, I will fix it. Any help would be greatly appreciated!
filename = input("Enter name of file: ")
file = open(filename, 'r+')
i = 0
alist = 
for element in file:
words = element.split()
for i in range(len(words)):
if len(words[i]) == 4:
i = i+1
file1 = open(filename, 'w')
for element in alist:
November 8th, 2012, 11:26 PM
I'd write the program with flex.
I did not test your program. I'd guess that
1) you have trouble identifying 4 letter words. Your program would remove "cat." from "I ate my cat."
2) You have trouble reconstructing the original.
If I had to use python I'd use the regular expression package,
With flex I'd also use regular expressions---it's so much easier.
[/code] are essential for python code and Makefiles!
November 10th, 2012, 08:16 AM
I have done something similar with Python using regex. I have popped my code below.
To format your code snippets you just need to highlight the text and click the # button which will wrap you selection with [CODE] tags.
file = open("C:\\test.txt", 'r+')
x = file.readlines()
x = str(x)
foo = re.compile(r"""aaaaa""", re.IGNORECASE)
bar = foo.sub('bbbbb', x)
Quick note - building regex patterns can be rather daunting so I find it helpful to use a piece of open source software called Kodos which you can find http://kodos.sourceforge.net/.
November 10th, 2012, 11:58 AM
I think this line is the problem:
Try changing that to: