gpt4 book ai didi

Python 用字典中的值替换键

转载 作者:行者123 更新时间:2023-12-01 05:02:11 25 4
gpt4 key购买 nike

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

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

最佳答案

我觉得这里不需要正则表达式,简单的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)

关于Python 用字典中的值替换键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com