2017-04-20 175 views
-2

我想寫一個文件,審查單詞「冬天」,但由於某種原因,我的代碼不工作,雖然我沒有錯誤。幫幫我!問題與審查蟒蛇腳本

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

開始通過固定的壓痕 – njzk2

+0

你的縮進是靠不住的。你能解決它嗎? – James

回答

1

發佈該問題時,您丟失了格式,因此很難準確地查看代碼的外觀。請修改該問題以解決該問題。

但我最初的猜測是censor函數永遠不會被調用。你只是聲明它,但它不會運行。

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