Python正则表达式用于字符串替换

2024-04-24 12:40:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想替换包含以下单词“$%word$%”的字符串部分 我想用字典的值替换它,而相应的关键字等于word。在

换句话说,如果我有一个字符串:“blahblahblah$%word$%blablablabla$%car$%” 还有一本字典{单词:'wassup',汽车:'toyota'}

字符串应该是“blahblahblah wassup blablablabla toyota”

如何在python中实现它,我在考虑使用字符串替换和regex。在


Tags: 字符串字典关键字单词car汽车regexword
3条回答

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

^{pr2}$

…或实现__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)

结果

^{pr2}$

re模块就是您想要的模块。在

不过,您可能需要重新考虑分隔符的选择。$%可能会有问题,因为$是regex中的保留字符。不过,请记住使用'\\$'或{}(这是一个原始字符串)。非常有用,如果你在python中做regex的东西。在

相关问题 更多 >