0

I am trying to replace all four letter words in a document that I read and replace it with four stars say. The code can identify the four letter words but it is not able to replace them. What am I doing incorrectly?

This is the code I have so far.

# wordfreq.py
import string

def compareItems((w1, c1),(w2,c2)):
    if c1 >c2:
        return -1
    elif c1 == c2:
        return cmp(w1, w2)
    else :
        return 1


def main() :
    print """This program analyzes word frequency in a file and
            prints a report on the n most frequent words. \n """

    # get the sequence of words from the file
    fname = raw_input("File to analyze: ")
    text = open(fname, 'r').read()
    text = str.lower(text)
    for ch in '!"#$%&()*+,-./:;<=>?@[[\\]^_`{|}`' :
        text = string.replace(text, ch, ' ')
    words = string.split(text) 

    # construct a dictionary of word counts
    counts = {}
    for w in words :
        if len(w) == 4:
            w.replace("w", "\****", )
    print words 


if __name__ == '__main__': main()
0

1 Answer 1

1

str.replace() returns the updated text, and you are trying to replace the string "w", not the value in the variable w. You don't really need to use str.replace() here; you have a list and you just need to replace all elements of length 4 with a different string.

Use a list comprehension to replace values in a list:

words = ['****' if len(w) == 4 else w for w in words]
print ' '.join(words)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.