Python 根据字典的内容替换文本的里的字符串

2024-11-13 09:35:16
推荐回答(3个)
回答1:

我觉得你好想想多了。即然全文替换。哪么你只需要遍历你的dict

a_dict = {'apple':'1','tree':'2','123456':'3'}
input_file = open(r'd:\test_body.txt',"r").read()();
for key,value in a_dict.items():
input_file=input_file.replace(key,value);

这样子不行吗?

回答2:

# encoding: utf-8
import re
patt = re.compile(r'\S+')

a_dict = {'apple':'1','tree':'2','123456':'3'}

content = '''# 第三行信息非严格匹配,不替换
apple 123456
123456 tree
appletree 12345678'''

a_dictkset = set(a_dict.keys())
def findkeys(ln):
return a_dictkset & set(patt.findall(ln))

def repln(ln, ks):
for k in ks:
ln = ln.replace(k, a_dict.get(k, k))
return ln

for ln in content.splitlines():
ln = repln(ln, findkeys(ln))
print ln

>python -u "rptest.py"
# 第三行信息非严格匹配,不替换
1 3
3 2
appletree 12345678
>Exit code: 0 Time: 0.051

回答3:

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> "%(pwd)s" % params
'secret'
>>> "%(pwd)s is not a good password for %(uid)s" % params
'secret is not a good password for sa'
>>> "%(database)s of mind, %(database)s of body" % params
'master of mind, master of body'

多看书