简体   繁体   中英

Replacing multiple words in a text file and writing new text to output file

I am trying to write a function which takes a text file as input file and create an output file with the same text with words replaced. This function will edit Emma with George, she with he and her with his.

My code is:

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

The out put file is created however blank.

Does anyone know how to get the output file with the edited text?

  • You never write the file.
  • You use i in two loops
  • You never close the infile
  • You don't respect the newlines
  • ...

Here an example that works

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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