![](/img/trans.png)
[英]how to convert string from known encoding to utf-8 on the fly in python?
[英]How to convert utf-8 encoding to a string?
我試圖預處理一些推文文本。 文本位於已被 tweepy 抓取的 csv 文件中。 我正在使用 Jupyter Notebook,讓我們假設它存儲在變量 'p' 中,當我使用單元格輸出輸出它時,文本看起來像這樣:
“b'@sarahbea34343 \\\\xf0\\\\x9f\\\\x98\\\\x94 I\\\\xe2\\\\x80\\\\x99m 不會過於樂觀,但是嘿...... https://twitter.com/icxdsfdf '”
相反,如果我在 Jupyter 中執行 print(p) 那么輸出是:
“b'@sarahbea34343 \\xf0\\x9f\\x98\\x94 I\\xe2\\x80\\x99m 不會過於樂觀,但是嘿...... https://twitter.com/icxdsfdf '”
我在互聯網上查了一下,這似乎是字節類 utf-8 編碼。 因此,我嘗試使用“.decode('utf-8')”進行解碼,但出現錯誤。 我發現的問題是,當它存儲在 csv 文件中時,utf-8 編碼被存儲為一個字符串,因此整個推文都是一個字符串。 這意味着即使反斜杠也被編碼為字符串。 我似乎不知道如何轉換它以便我可以刪除這些表情符號和其他字符的 utf 編碼?
我嘗試了多種導致再次返回相同字符串的方法,例如:
p.encode('ascii','ignore').decode('ascii')
或 p.encode('latin-1').decode('utf-8').encode('ascii', 'ignore')
如果文本確實是這樣存儲的(因此您正在以文本模式 'r' 讀取文件),則可以執行以下操作:
# Strip leading b and inner quotes
s = "b'@sarahbea34343 \xf0\x9f\x98\x94 I\xe2\x80\x99m not going in overly optimistic tbh but hey... https://twitter.com/icxdsfdf'"[2:-1]
# Encode as latin-1 to get bytes, decode from unicode-escape to unescape
# the byte expressions (\\xhh -> \xhh), encode as latin-1 again to get
# bytes again, then finally decode as UTF-8.
new_s = encode('latin-1').decode('unicode-escape').encode('latin-1').decode('utf-8')
print(new_s)
@sarahbea34343 😔 I’m not going in overly optimistic tbh but hey... https://twitter.com/icxdsfdf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.