替换python中的四个字母单词

时间:2012-11-08 07:17:15

标签: python replace words

我正在尝试编写一个打开文本文档的程序,并用 * *替换所有四个字母单词。我现在一直在搞乱这个程序多个小时。我似乎无法到达任何地方。我希望有人能够帮助我解决这个问题。这是我到目前为止所拥有的。非常感谢帮助!

def censor():
    filename = input("Enter name of file: ")
    file = open(filename, 'r')
    file1 = open(filename, 'w')
    for element in file:
        words = element.split()
        if len(words) == 4:
            file1 = element.replace(words, "xxxx")
            alist.append(bob)
        print (file)
    file.close()

这里是修订版的verison,我不知道这是否更好

def censor():
    filename = input("Enter name of file: ")
    file = open(filename, 'r')
    file1 = open(filename, 'w')
    i = 0
    for element in file:
        words = element.split()
        for i in range(len(words)):
            if len(words[i]) == 4:
                file1 = element.replace(i, "xxxx")
                i = i+1
    file.close()

5 个答案:

答案 0 :(得分:2)

for element in file:
    words = element.split()
    for word in words:
        if len(word) == 4:
            etc etc

原因如下:

说你文件中的第一行是“你好,我叫约翰” 然后是循环的第一次迭代:element = 'hello, my name is john'words = ['hello,','my','name','is','john']

您需要检查每个单词内部的内容for word in words

同样可能值得注意的是,在您当前的方法中,您不会注意标点符号。请注意上面words中的第一个单词...

要摆脱标点符号而不是说:

import string

blah blah blah ...
for word in words:
    cleaned_word = word.strip(string.punctuation)
    if len(cleaned_word) == 4:
       etc etc

答案 1 :(得分:1)

这是一个提示:len(words)返回当前行的单词数,而不是任何特定单词的长度。您需要添加代码来查看生产线上的每个单词并确定是否需要替换它。

此外,如果文件比简单的单词列表更复杂(例如,如果它包含需要保留的标点符号),则可能需要使用正则表达式来完成这项工作。

答案 2 :(得分:0)

可能是这样的:

def censor():
    filename = input("Enter name of file: ")
    with open(filename, 'r') as f:
        lines = f.readlines()

    newLines = []
    for line in lines:
        words = line.split()
        for i, word in enumerate(words):
            if len(word) == 4:
                words[i] == '**'
        newLines.append(' '.join(words))

    with open(filename, 'w') as f:
        for line in newLines:
            f.write(line + '\n')

答案 3 :(得分:0)

您需要在第4行w替换w+中的字母file1 = open(filename, 'w')file1 = open(filename, 'w+')必须是import os import time localtime = time.asctime( time.localtime(time.time()) ) a = input("What is your first name? ").title() b = input("And your last name? ").title() c = input("What is your e-mail adderess? ") d = input("And your phone number? ") f = input("When were you born? (02-01-1900 is 1 February 1900)") print(a) print(b) print(c) print(d) print(f) e = input("Is this correct? (Y\N) ") g = (a+"-"+b) if e == "Y" or "y": new_path = '/users/Pivo/registreren/%s.txt' % g new_days = open(new_path,'w+') new_days.write(localtime) new_days.write('\n') new_days.write(a) new_days.write(" ") new_days.write(b) new_days.write('\n') new_days.write(c) new_days.write('\n') new_days.write(d) new_days.write('\n') new_days.write(f) new_days.write('\n') new_days.write('\n') new_days.write('\n') new_days.write('\n') new_days.close() print("Okay, done!") if e == "N" or "n": os.startfile("C:/Users/Pivo/registreren/registreren.py") (我正在处理这个项目,所以这是我的代码)

GetCartItems

答案 4 :(得分:0)

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()