我正在尝试编写一个审查"冬季"一词的文件,但是由于某种原因,尽管我没有错误,但我的代码不起作用。帮助!
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)
in_text_file.close()
out_text_file.close()
审查的一种方法是在读取文件上运行 replace
。
一个简单的示例:
file1 = open("filetobecensored.txt")
file2 = open("winter_censored.txt", "w")
word = "winter"
file2.write(file1.read().replace(word, "*"*len(word)))
file1.close()
file2.close()
发布问题时丢失了格式,因此很难确切地看到您的代码是什么样子。请编辑问题以解决这个问题。
,但我最初的猜测是censor
功能从未被调用。您只会声明它,但不会运行。