Replace four letter word in python

前端 未结 5 974
暗喜
暗喜 2020-12-12 08:24

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 hour

5条回答
  •  渐次进展
    2020-12-12 08:57

    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
    

提交回复
热议问题