python re.sub with variable

时间:2015-01-13 00:21:56

标签: python regex

输入文字:

Ell és la víctima que expia els nostres pecats, i no tan sols els nostres, sinó els del món sencer.  

预期产出:

Ell és la víctima que expia els nostres pecats, i no tan sols els nostres, sinó els del món sencer.

已知事实: unichr(233)=é

现在我有

re.sub('&#([^;]*);', r'unichr(int(\1))', inputtext, flags=re.UNICODE)

当然不起作用,不知道如何在\1上传递函数

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

使用lambda function

re.sub('&#([^;]*);', lambda match: unichr(int(match.group(1))), t, flags=re.UNICODE)

答案 1 :(得分:4)

幸运的是,re.sub也接受一个函数作为参数。该函数将接收"MatchObject" - 从那里,您可以通过match.group(1), match.group(2)等获得匹配的组。函数的返回值将是替换输入中匹配组的字符串文本。

def fn(match):
  return unichr(int(match.group(1)))

re.sub('&#([^;]*);', fn, inputtext, flags=re.UNICODE)

如果你真的想要,你可以内联这个并使用lambda - 但我认为lambda使得在这种情况下更难阅读 1


顺便说一句,根据你的python版本,有更好的方法来解除html(因为它也会处理像'&'这样的特殊转义序列:

Python2.x

>>> import HTMLParser
>>> s = 'Ell és la víctima que expia els nostres pecats, i no tan sols els nostres, sinó els del món sencer.'
>>> print HTMLParser.HTMLParser().unescape(s)
Ell és la víctima que expia els nostres pecats, i no tan sols els nostres, sinó els del món sencer.

Python3.x

>>> import html
>>> html.unescape(s)

reference

1 特别是如果你给fn一个更明智的名字; - )