mab*_*sif 1 python regex string
我想替换包含以下单词"$%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)
Run Code Online (Sandbox Code Playgroud)
如果要在使用时传递替换表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)
Run Code Online (Sandbox Code Playgroud)
......或实施的课程__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)
Run Code Online (Sandbox Code Playgroud)