python re.sub 带变量

python re.sub with variable

输入文字:

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())', inputtext, flags=re.UNICODE)

当然不工作,不知道如何在

上传递函数

有什么想法吗?

使用 lambda function:

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

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

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 一个更合理的名字;-)