3

我的正则表达式需要匹配一个句子中的两个单词,但只需要替换第二个单词。第一个词实际上是字典的键,其中获取第二个词的替代项。在 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中完成?

4

1 回答 1

3

像这样的东西:

>>> 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 提取到命名函数中看起来会更好。

于 2012-04-05T09:23:22.133 回答