2017-04-22 79 views
1

使用python從用戶輸入文件審查單詞「冬天」 - 「y.txt」寫了一些代碼,但我遇到了錯誤。任何發生的「冬季」一詞都應該消失。幫助和感謝!從文本文件審查單詞並創建新文件

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

你得到什麼錯誤? – dartdog

+0

@dartdog剛剛編輯了這個問題! – teresawithoutah

+1

你永遠不會定義「文本」併爲其分配內容 – dartdog

回答

0

字冬季不帶引號:御史(冬季,文件名)應該是御史( 「冬天」,文件名)或審查(文字,文件名)

編輯:您還需要打開文件並在文本變量中讀入一行。

就我個人而言,我會使用正則表達式來避免帶句點的陷阱。

import re 

然後爲每個行:

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