Please support our Python advertiser: Programming Forums
Views: 797 | Replies: 2
![]() |
•
•
Join Date: Mar 2007
Location: Georgia
Posts: 13
Reputation:
Rep Power: 2
Solved Threads: 0
This is what I have. I know I am missing something can you help
[code = python]import string
def main():
print "This program replaces 4 lettter words in a file with xxxx"
# get the sequence of words from the file
fname = raw_input("File to analyze: ")
text = open(fname,'r').read()
text = string.lower(text)
for ch in '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~':
text = string.replace(text, ch, ' ')
words = string.split(text)
wordCount = len(words)
ch = string.split(words)
charCount = len(ch)
if charCount == 4:
oldword = string.join(ch)
newtext = string.join(text)
o = open(fname,a)
for line in open(fname):
line = line.replace(oldword,newword)
o.write(line + "\n")
o.close()
text.close()
main()[/code]
[code = python]import string
def main():
print "This program replaces 4 lettter words in a file with xxxx"
# get the sequence of words from the file
fname = raw_input("File to analyze: ")
text = open(fname,'r').read()
text = string.lower(text)
for ch in '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~':
text = string.replace(text, ch, ' ')
words = string.split(text)
wordCount = len(words)
ch = string.split(words)
charCount = len(ch)
if charCount == 4:
oldword = string.join(ch)
newtext = string.join(text)
o = open(fname,a)
for line in open(fname):
line = line.replace(oldword,newword)
o.write(line + "\n")
o.close()
text.close()
main()[/code]
I didn't have a file, so I used just a text string for testing, but here is one way you can solve this:
python Syntax (Toggle Plain Text)
text = "I love to work, but not paying my taxes!" # text to word list words = text.split() print words # testing the word list # now comes the processing part new_words = [] for word in words: # remove certain punctuations for c in '?!,.;:': if c in word: word = word.replace(c, '') # it's a 4 letter word, replace with 'xxxx' if len(word) == 4: word = 'xxxx' new_words.append(word) # list back to text print ' '.join(new_words)
No one died when Clinton lied.
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)






Linear Mode