Replacing words in text file using a dictionary

前端 未结 6 1457
青春惊慌失措
青春惊慌失措 2021-01-12 13:25

I\'m trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file

6条回答
  •  一整个雨季
    2021-01-12 13:36

    This is how I would do it:

    fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}
    
    with open('yourfile.txt', 'w+') as f:
        s = f.read()
        for key in fields:
            s = s.replace(key, fields[key])
        f.write(s)
    

提交回复
热议问题