Dav*_*ing 6 python dictionary in-place python-2.7
我正在尝试打开一个文本文件,然后通读它,将某些字符串替换为存储在词典中的字符串。
基于“ 如何在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)
我曾经items()重复过key你values的fields字典。
我用 跳过空行并continue用 清理其他行rstrip()
keys我将在 the 中找到的所有内容替换为您字典中的linethe ,并用 写每一行。valuesfieldsprint
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4940 次 |
| 最近记录: |