Python用字典中的值替换键
我有一本字典:Python用字典中的值替换键,python,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 r
['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
re
。您只需对输入d:@mu执行無 是的,那是真的,谢谢你指出:)不过那只是个人的喜好。。除息的