使用字典替换文本文件中的单词
问题内容:
我正在尝试打开一个文本文件,然后通读它,将某些字符串替换为存储在词典中的字符串。
基于“如何在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()
遍历key
和values
您的fields
字典。
我跳过空白行,continue
并用清理其他行rstrip()
我用您的字典keys
中的替换line
了values
在中找到的fields
所有行,并用编写了每一行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