繁体   English   中英

替换文本文件中的多个单词并将新文本写入输出文件

[英]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()

输出文件已创建,但是为空白。

有谁知道如何获得带有已编辑文本的输出文件?

  • 您永远不会写入文件。
  • 您在两个循环中使用i
  • 您永远不会关闭文件
  • 你不尊重换行符
  • ...

这是一个有效的例子

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM