Replacing words in text file using a dictionary

前端 未结 6 1502
青春惊慌失措
青春惊慌失措 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:27

    import fileinput
    
    text = "sample file.txt"
    fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}
    
    for line in fileinput.input(text, inplace=True):
        line = line.rstrip()
        for field in fields:
            if field in line:
                line = line.replace(field, fields[field])
    
        print line
    

提交回复
热议问题