审查文本文件中的单词并创建新文件

时间:2017-04-22 03:10:35

标签: python function file

使用python审查单词" winter"来自用户输入文件 - " y.txt" 写了一些代码,但我遇到了错误。任何出现的单词" winter"应该走了。帮助和谢谢!

filename = input("Enter file name (without extension): ")
file1 = filename+".txt"
file2 = filename+"_censored.txt"

word = input("Enter the word you are searching for: ")
#In this case, the input would be "winter"

print("\nLooping through the file, line by line.")

in_text_file = open(file1, "r")

out_text_file = open(file2,"w")

for line in in_text_file:
    print(line)
out_text_file.write(line)

n = [ ]

def censor(word, filename):
   for i in text.split(""):
        if i == word:
            i = "*" * len(word)
            n.append(i)
        else:
            n.append(i)
            return "".join(n)

censor(word,filename)

in_text_file.close()
out_text_file.close()

我得到了错误 enter image description here

1 个答案:

答案 0 :(得分:0)

单词winter没有引用:censor(winter,filename)应该是censor(" winter",filename)或者censor(word,filename)

编辑:您还需要打开文件并在文本变量中读取一行。

就个人而言,我会使用正则表达式来避免陷入句点。

import re

然后为每一行:

line = re.sub(r'(^| )word here($| |\.|,|\;)','*****',line);
相关问题