我的正则表达式需要匹配一个句子中的两个单词,只有第二个单词需要替换.第一个单词实际上是一个关键字,使用该关键字可以从字典中获取替代单词.在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提取到命名函数看起来会更好.