Replace four letter word in python

前端 未结 5 966
暗喜
暗喜 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:47

    def censor(filename):
    """Takes a file and writes it into file censored.txt with every 4-letterword replaced by xxxx"""
    infile = open(filename)
    content = infile.read()
    infile.close()
    outfile = open('censored.txt', 'w')
    table = content.maketrans('.,;:!?', '      ')
    noPunc = content.translate(table) #replace all punctuation marks with blanks, so they won't tie two words together
    wordList = noPunc.split(' ')
    for word in wordList:
        if '\n' in word:
            count = word.count('\n')
            wordLen = len(word)-count
        else:
            wordLen = len(word)
        if wordLen == 4:
            censoredWord = word.replace(word, 'xxxx ')
            outfile.write(censoredWord)
        else:
            outfile.write(word + ' ')
    outfile.close()
    

提交回复
热议问题