在Python中转义HTML实体和UTF8

2024-05-08 12:05:51 发布

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

我正在分析一个包含许多特殊字符(Unicode和HTML实体形式)的HTML文件。 尽管使用Python阅读了很多关于Unicode的文档,但是我仍然不能正确地转换HTML实体。在

下面是我做的测试:

>>> import HTMLParser
>>> p = HTMLParser.HTMLParser()
>>> s = p.unescape("‹")
>>> repr(s)
"u'\\x8b'"
>>> print s 
‹ # !!!
>>> s
u'\x8b'
>>> print s.encode("latin1")
‹ # OK, it prints fine in latin1, but I need UTF-8 ...
>>> print s.encode("utf8")
‹ # !!!

>>> import codecs
>>> out = codecs.open("out8.txt", encoding="utf8", mode="w")
>>> out.write(s)
# Viewing the file as ANSI gives me ‹ # !!!
# Viewing the file as UTF8 gives NOTHING, as if the file were empty # !!!

将未转义字符串写入UTF8文件的正确方法是什么?


Tags: 文件theimport实体htmlasunicodeutf8
1条回答
网友
1楼 · 发布于 2024-05-08 12:05:51

U+008B是一个控制字符,因此什么都看不到是正常的。”媫”是U+2039单左指角引号,并且不是拉丁语-1。它,然而,CP1252中的字符0x8B。并且停止依赖Windows控制台输出来告诉您什么是正确的,除非您事先运行chcp 65001。在

相关问题 更多 >