2024-04-24 12:40:25 发布
网友
我想替换包含以下单词“$%word$%”的字符串部分 我想用字典的值替换它,而相应的关键字等于word。在
换句话说,如果我有一个字符串:“blahblahblah$%word$%blablablabla$%car$%” 还有一本字典{单词:'wassup',汽车:'toyota'}
字符串应该是“blahblahblah wassup blablablabla toyota”
如何在python中实现它,我在考虑使用字符串替换和regex。在
将re.sub与函数一起用作repl参数:
re.sub
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:
functools.partial
…或实现__call__的类:
__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)
import re text = "blahblahblah $%word$% blablablabla $%car$%" words = dict(word="wassup", car="toyota") regx = re.compile('(\$%%(%s)\$%%)' % '|'.join(words.iterkeys())) print regx.sub(lambda mat: words[mat.group(2)], text)
结果
re模块就是您想要的模块。在
re
不过,您可能需要重新考虑分隔符的选择。$%可能会有问题,因为$是regex中的保留字符。不过,请记住使用'\\$'或{}(这是一个原始字符串)。非常有用,如果你在python中做regex的东西。在
$%
$
'\\$'
将
re.sub
与函数一起用作repl参数:如果要在使用
^{pr2}$re.sub
时传递替换表,请使用functools.partial
:…或实现
__call__
的类:结果
^{pr2}$re
模块就是您想要的模块。在不过,您可能需要重新考虑分隔符的选择。}(这是一个原始字符串)。非常有用,如果你在python中做regex的东西。在
$%
可能会有问题,因为$
是regex中的保留字符。不过,请记住使用'\\$'
或{相关问题 更多 >
编程相关推荐