2 回答

TA貢獻1818條經驗 獲得超3個贊
我認為您在上面遇到的問題是您的文本已經是 unicode 格式,而您正試圖將其再次轉換為 unicode,這導致了您的錯誤。
下面的代碼對我有用,并給出了如下所示的輸出。
from bs4 import BeautifulSoup
text = "Albert Einstein’s Theory of Relativity: Should We Worry…?"
parsed_html = BeautifulSoup(text)
print 'Original Type: ' + type(text)
print 'Original Text: ' + text
print 'Parsed Type: ' + type(parsed_html.text)
print 'Parsed Text: ' + parsed_html.text
輸出:
Original Type: <type 'str'>
Original Text: Albert Einstein’s Theory of Relativity: Should We Worry…?
Parsed Type: <type 'unicode'>
Parsed Text: Albert Einstein’s Theory of Relativity: Should We Worry…?
使用 BeautifulSoup4 版本 4.7.1
點安裝 bs4

TA貢獻1875條經驗 獲得超5個贊
事實證明,原因HTMLEntitiesToUnicode()
對我不起作用是因為我正在從 .json 文件中讀取數據,該文件已寫入但未指示應將其保存在 .json 文件中utf-8
。解決這個問題,然后HTMLEntititesToUnicode()
如上所述使用效果很好。
添加回答
舉報