我正在解析包含許多特殊字符(包括Unicode和HTML實體形式)的HTML文件。 儘管已經閱讀了大量有關Python與Unicode的文檔,但我仍然無法正確轉換HTML實體。在Python中轉義HTML實體和UTF-8
這裏是我跑的測試:
>>> 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 # !!!
什麼是寫作的轉義字符串s到UTF8文件的正確方法是什麼?
您是否在Windows中的命令提示符下,偶然? –
如果您的交互式會話本身在utf-8終端上運行,您將只能看到UTF-8編碼打印的正確輸出。它不是,因爲如果它在哪裏,編碼爲「latin1」的打印將會失敗。 – jsbueno
爲了解決有關會話編碼的問題,'locale'命令的輸出確認它是UTF-8。 (我在Linux下) –