Python、XML和233类型编码

2024-04-23 12:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Convert XML/HTML Entities into Unicode String in Python

我正在用Python阅读excelxml文档。最后我演了很多角色,比如 &;233

各种不同的字母代表着不同的口音。有没有一种简单的方法可以把这些字符转换成utf-8?在


Tags: in文档角色convertstringhtml字母unicode
2条回答

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

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

对于python2.x,对于3.x,导入是import html.parser

使用这个QandA和另一个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

相关问题 更多 >