我想替换包含以下单词“$%word$%”的字符串的一部分 我想用字典的值替换它,对应的键等于 word。
换句话说,如果我有一个字符串:“blahblahblah $%word$% blablablabla $%car$%” 和一本字典 {word:'wassup', car:'toyota'}
字符串将是“blahblahblah wassup blablablabla toyota”
如何在 python 中实现它,我正在考虑使用字符串替换和正则表达式。
请您参考如下方法:
将 re.sub 与函数一起用作 repl 参数:
import re
text = "blahblahblah $%word$% blablablabla $%car$%"
words = dict(word="wassup", car="toyota")
def replacement(match):
try:
return words[match.group(1)] # Lookup replacement string
except KeyError:
return match.group(0) # Return pattern unchanged
pattern = re.compile(r'\$%(\w+)\$%')
result = pattern.sub(replacement, text)
如果想在使用re.sub的时候传递替换表,使用functools.partial:
import functools
def replacement(table, match):
try:
return table[match.group(1)]
except:
return match.group(0)
table = dict(...)
result = pattern.sub(functools.partial(replacement, table), text)
...或实现 __call__ 的类:
class Replacement(object):
def __init__(self, table):
self.table = table
def __call__(self, match):
try:
return self.table[match.group(1)]
except:
return match.group(0)
result = pattern.sub(Replacement(table), text)
