我正在尝试打开一个文本文件,然后通读它,用存储在字典中的字符串替换某些字符串。
根据以下问题的答案如何在 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
I used items()迭代key
and values
你的fields
dict.
我跳过空白行continue
并用清洁其他的rstrip()
我替换每个keys
发现于line
by the 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)