我的正则表达式需要在一个句子中匹配两个单词,但只需要替换第二个单词。第一个单词实际上是字典的一把钥匙,在字典中,第二个单词的替代词被提取出来。在PERL中,它看起来像:
$sentence = "Tom's boat is blue";
my %mydict = {}; # some key-pair values for name => color
$sentence =~ s/(\S+)'s boat is (\w+)/$1's boat is actually $mydict{$1}/;
print $sentence;
在python中如何实现这一点?
最佳答案
像这样的:
>>> sentence = "Tom's boat is blue"
>>> mydict = { 'Tom': 'green' }
>>> import re
>>> re.sub("(\S+)'s boat is (\w+)", lambda m: "{}'s boat is actually {}".format(m.group(1), mydict[m.group(1)]), sentence)
"Tom's boat is actually green"
>>>
不过,将lambda提取到一个命名函数会更好。
关于python - 如何使用字典值在Python中进行正则表达式替换,其中键是同一字符串中的另一个匹配对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10025881/