python – 使用字典替换文本文件中的单词

我正在尝试打开一个文本文件,然后读取它用字典中存储的字符串替换某些字符串.

根据How do I edit a text file in Python?的答案,我可以在进行替换之前提取字典值,但循环遍历字典似乎更有效.

代码不会产生任何错误,但也不会进行任何替换.

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 i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)


             print line

最佳答案 我使用
items()迭代你的字段dict的键和值.

我跳过空白行继续并用rstrip()清理其他行

我用字段dict中的值替换行中找到的每个键,然后用print打印每行.

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()
    if not line:
        continue
    for f_key, f_value in fields.items():
        if f_key in line:
            line = line.replace(f_key, f_value)
    print line
点赞