使用 Python 編碼和解碼 MIME quoted-printable 資料


很多時候我們都需要處理的資料並不總是包含常規 ASCII 字元。例如,一封用非英語撰寫的電子郵件。Python 有一個基於 MIME(多用途網際網路郵件擴充套件)的模組,可以用它來處理此類字元。在本文中,我們將瞭解如何解碼電子郵件或其他一些直接輸入中的此類字元。

使用 email 包

email 包包含 mime 和 charset 模組,它們可以執行編碼和解碼工作,如下例所示。我們獲取了一封包含 Unicode 字元的電子郵件,然後將其編碼為 utf-8。

示例

import email.mime, email.mime.nonmultipart, email.charset
msg=email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8')

#Construct a new charset
cs=email.charset.Charset('utf-8')
cs.body_encoding = email.charset.QP

# Set the content using the new charset
msg.set_payload(u'This is the text containing ünicöde', charset=cs)
print(msg)

執行以上程式碼後,會得到以下結果 -

輸出

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable

This is the text containing =C3=BCnic=C3=B6de

使用 quopri

此 python 模組可以進行 quoted-printable 傳輸編碼和解碼。quoted-printable 編碼專為不包含過多的不可列印字元的資料而設計。在以下示例中,我們將看到如何對含有非常規 ASCII 字元的字串進行編碼和解碼。

示例

import quopri
str1 = 'äé'
#encoded = quopri.encodestring('äé'.encode('utf-8'))
encoded = quopri.encodestring(str1.encode('utf-8'))
print(encoded)

str2 = '=C3=A4=C3=A9'
decoded_string = quopri.decodestring(str2)
print(decoded_string.decode('utf-8'))

執行以上程式碼後,會得到以下結果 -

輸出

b'=C3=A4=C3=A9'
äé

更新於: 2020-12-28

2K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告