2011-02-18 47 views

回答

5

我不知道有內置的庫或沒有,但這裏是快速和骯髒的方式做正則表達式

>>> import re 
>>> re.sub("&#(\d+);",lambda x:unichr(int(x.group(1),10)),": or .") 
u': or .' 
+0

馬克:謝謝你! – Shane 2011-02-18 12:42:05

2

像這樣的事情會處理大多數實體定義(假設的Python 2.x的)。它處理十進制,十六進制和htmlentitydefs中的任何命名實體。

import re 
from htmlentitydefs import name2codepoint 
EntityPattern = re.compile('&(?:#(\d+)|(?:#x([\da-fA-F]+))|([a-zA-Z]+));') 
def decodeEntities(s, encoding='utf-8'): 
    def unescape(match): 
     code = match.group(1) 
     if code: 
      return unichr(int(code, 10)) 
     else: 
      code = match.group(2) 
      if code: 
       return unichr(int(code, 16)) 
      else: 
       code = match.group(3) 
       if code in name2codepoint: 
        return unichr(name2codepoint[code]) 
     return match.group(0) 

    if isinstance(s, str): 
     s = s.decode(encoding) 
    return EntityPattern.sub(unescape, s) 
相關問題