使用字典替换文本文件中的单词 [英] Replacing words in text file using a dictionary
问题描述
我正在尝试打开一个文本文件,然后通读它,用存储在字典中的字符串替换某些字符串.
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.
基于对>我如何编辑文本文件的答案在Python中?在进行替换之前,我可以拔出字典值,但是循环遍历字典似乎更有效.
Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
该代码不会产生任何错误,但也不会进行任何替换.
The code doesn't produce any errors, but also doesn't do any replacing.
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
推荐答案
我使用了我用continue
跳过空白行,并用rstrip()
I skip the blank lines with continue
and clean the others with rstrip()
我用fields
字典中的values
替换了line
中找到的所有keys
,并用print
编写了每一行.
I replace every keys
found in the line
by the values
in your fields
dict, and I write every lines with 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
这篇关于使用字典替换文本文件中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!