我正在尝试用 Python 和 BeautifulSoup 解析这个文档:
http://en.wikipedia.org/w/api.php?format=xml&action=opensearch&search=rage_against_the_machine
第七个 Item 作为这个 Text 标签:
Rage Against the Machine's 1994–1995 Tour
当我尝试打印文本“Rage Against the Machine's 1994–1995 Tour”时,python 给我这个:
UnicodeEncodeError: 'ascii' 编解码器无法对位置 31 中的字符 u'\u2013' 进行编码:序号不在范围内 (128)
我可以通过简单地将 u'\u2013' 替换为 '-' 来解决它,如下所示:
itemText = itemText.replace(u'\u2013', '-')
但是我没有编码的每个字符呢?我不想忽略它们,也不想列出所有可能的查找和替换。
当然,必须存在一个库来尝试最好地从常见的已知编码列表中检测编码(但很可能会弄错)。
someText = getTextWithUnknownEncoding(someLocation);
bestAsciiAttemptText = someLibrary.tryYourBestToConvertToAscii(someText)
谢谢
请您参考如下方法:
将其解码为 UTF-8 应该可行:
itemText = itemText.decode('utf-8')
