繁体   English   中英

Python用字典中的值替换键

[英]Python replacing keys with values in dictionary

我有一个字典,例如: ['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()

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

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

>>> 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)

预期可以正常工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM