[英]Replacing multiple words in a text file and writing new text to output file
我正在嘗試編寫一個函數,該函數將文本文件作為輸入文件,並用替換為單詞的相同文本創建輸出文件。 此功能將編輯Emma和George,她和他以及他和他。
我的代碼是:
switch = {"Emma":"George", "she":"he", "hers":"his"}
def editWords(fin):
#open the file
fin = open(filename, "r")
#create output file
with open("Edited.txt", "w") as fout:
#loop through file
for line in fin.readlines():
for word in switch.keys():
if word in line.split():
line = line.replace(word, switch[word])
fout.write(line)
fin.close()
輸出文件已創建,但是為空白。
有誰知道如何獲得帶有已編輯文本的輸出文件?
這是一個有效的例子
switch = {"Emma":"George", "she":"he", "hers":"his"}
def editWords(filename):
#open the file
fin = open(filename, "r")
#create output file
with open("/tmp/Edited", "w") as fout:
#loop through file
for line in fin.readlines():
for word in switch.keys():
if word in line.split():
line = line.replace(word, switch[word])
fout.write(line)
fin.close()
editWords("/tmp/filename")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.