Python用字典中的值替换键

时间:2014-09-14 13:52:40

标签: python

我有一个字典:['snow side':'ice','tea time':'coffee']。我需要用文本文件中的值替换密钥。

我有一个文字:

I seen area at snow side.I had tea time.
I am having good friends during my teatime.

转换为:

I seen area at ice.I had coffee.
I am having good friends during my coffee.

编码:

import re
dict={'snow side':'ice','tea time':'coffee'}
with open('text3.txt', 'r+') as f:
    content = f.read()
    for key,values in dict:
        matched = re.search(r'\.\(.*?\)', key)
        replaced = re.sub(r'\.\(.*?\)', '.(' + values + ')', values)
        f.seek(0)
        f.write(replaced)
        f.truncate()

请帮我修改我的代码!将不胜感激!

2 个答案:

答案 0 :(得分:1)

我不认为这里需要正则表达式,一个简单的replace也应该起作用

>>> text = """I seen area at snow side.I had tea time.
... I am having good friends during my teatime."""
>>> 
>>> dict={'snow side':'ice','teatime':'coffee'}
>>> 
>>> for key in dict:
...     text = text.replace(key, dict[key])
... 
>>> print text
I seen area at ice.I had tea time.
I am having good friends during my coffee.

因此,您的原始示例将更改为:

dict={'snow side':'ice','tea time':'coffee'}
with open('text3.txt', 'r+') as f:
    content = f.read()
for key in dict:
    content = content.replace(key, dict[key])
with open('text3.txt', 'w') as f:
    f.write(content)

答案 1 :(得分:1)

预计会有效:

d = {'snow side': 'ice', 'tea time': 'coffee'}
with open('text3.txt', 'r+') as f:
    content = f.read()
    for key in d:
        content.replace(key, d[key])
    f.seek(0)
    f.write(content)
    f.truncate()

另外,会覆盖dict等内置名称。