簡體   English   中英

用Python解碼和編碼

[英]Decoding and Encoding in Python

我有一些要在Python中解碼和編碼的文本

import html.parser

original_tweet = "I luv my <3 iphone & you’re awsm 
                 apple.DisplayIsAwesome, sooo happppppy 🙂 
                 http://www.apple.com"
tweet = original_tweet.decode("utf8").encode('ascii', 'ignore')

我已經在Spyder(Python 3.6)的一行中輸入了原始推文

我收到以下消息

AttributeError: 'str' object has no attribute 'decode'

有沒有其他方法可以為Python 3.6重寫此代碼?

在Python3 +中,您的original_tweet字符串是UTF-8編碼的Unicode字符串,其中包含Unicode emoji表情 由於Unicode中的65k +字符是256個ASCII字符的超集,因此您不能簡單地將Unicode字符串轉換為ASCII字符串。

但是,如果你可以用一些數據丟失的生活(即下降表情符號),那么你可以嘗試以下方法(見相關的問題):

original_tweet = "I luv my <3 iphone & you’re awsm ..."

# Convert the original UTF8 encoded string into an array of bytes.
original_tweet_bytes = original_tweet.encode("utf-8")

# Decode that array of bytes into a string containing only ASCII characters;
# pass errors="strict" to find failing character mappings, and I also suggest
# to read up on the option errors="replace".
original_tweet_ascii = original_tweet_bytes.decode("ascii", errors="ignore")

或作為簡單的單線:

tweet = original_tweet.encode("utf-8").decode("ascii", errors="ignore")

請注意,這轉換的HTML實體 < & 您可能需要分別解決。 您可以使用適當的HTML解析器(例如lxml )或使用簡單的字符串替換來做到這一點:

tweet = tweet.replace("&lt;", "<").replace("&amp;", "&")

或者從Python 3.4+開始,您可以像這樣使用html.unescape()

tweet = html.unescape(tweet)

另請參閱此問題,以了解如何處理字符串中的HTML實體。

附錄。 Python的Unidecode軟件包似乎也為此提供了有用的功能,盡管在其當前版本中它不處理表情符號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM