Python,XML,é类型编码

时间:2012-12-18 08:09:19

标签: python xml unicode

  

可能重复:
  Convert XML/HTML Entities into Unicode String in Python

我正在使用Python阅读excel XML文档。我最终得到了许多人物,比如      &安培;#233;

代表各种重音字母(等)。有没有一种简单的方法将这些字符转换为utf-8?

2 个答案:

答案 0 :(得分:1)

如果您只想将HTML实体解析为其等效的unicode:

>>> import HTMLParser
>>> parser = HTMLParser.HTMLParser()
>>> parser.unescape('é')
u'\xe9'
>>> print parser.unescape('é')
é

这适用于Python 2.x,对于3.x,导入为import html.parser

答案 1 :(得分:0)

使用此QandA和另一个的提示,我有一个似乎有效的解决方案。它需要整个文档并从文档中删除所有html实体。

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value