我正在尝试编写一个审查“冬天”这个词的文件,但由于某些原因我的代码没有工作,尽管我没有错误。救命!
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()
答案 0 :(得分:2)
审查它的一种方法是在读取文件上运行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()
答案 1 :(得分:1)
发布问题时丢失了格式,因此很难确切地看到代码的样子。请编辑问题以解决此问题。
但我最初的猜测是永远不会调用censor
函数。你只是宣布它,但它不会运行。