0

可能重复:
在 Python 中将 XML/HTML 实体转换为 Unicode 字符串

我正在使用 Python 阅读一个 excel XML 文档。我最终得到了很多字符,例如 é

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

4

2 回答 2

1

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

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

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

于 2012-12-18T08:21:52.337 回答
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
于 2012-12-18T18:34:28.490 回答