Python 2.7 - find and replace from text file, using dictionary, to new text file

后端 未结 3 869
别跟我提以往
别跟我提以往 2021-01-05 17:27

I am newbie to programming, and have been studying python in my spare time for the past few months. I decided I was going to try and create a little script that converts Ame

3条回答
  •  执念已碎
    2021-01-05 17:53

    As all the good answers above, I wrote a new version which I think is more pythonic, wish this helps:

    # imported dictionary contains 1800 english:american spelling key:value pairs.
    mydict = {
        'color': 'colour',
    }
    
    
    def replace_all(text, mydict):
        for english, american in mydict.iteritems():
            text = text.replace(american, english)
        return text
    
    try:
        with open('new_output.txt', 'w') as new_file:
            with open('test_file.txt', 'r') as f:
                for line in f:
                    new_line = replace_all(line, mydict)
                    new_file.write(new_line)
    except:
        print "Can't open file!"
    

    Also you can see the answer I asked before, it contains many best practice advices: Loading large file (25k entries) into dict is slow in Python?

    Here is a few other tips about how to write python more python:) http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

    Good luck:)

提交回复
热议问题