小编Dav*_*ing的帖子

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

我正在尝试打开一个文本文件,然后通读它,将某些字符串替换为存储在词典中的字符串。

基于“ 如何在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
Run Code Online (Sandbox Code Playgroud)

python dictionary in-place python-2.7

6
推荐指数
1
解决办法
4940
查看次数

标签 统计

dictionary ×1

in-place ×1

python ×1

python-2.7 ×1