我們目前正在構建一個通過 Django 將文本存盤在 PostgreSQL 資料庫中的系統。然后通過 PGSync 將資料提取到 ElasticSearch。
目前我們在一個測驗用例中遇到了以下問題
錯誤資訊:
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 159-160: surrogates not allowed
我們確定了導致該問題的角色。這是一個表情符號。
文本本身是希臘字符、“英文字符”和看起來像表情符號的混合體。希臘語不顯示為希臘語,而是以\u形式顯示。
導致問題的相關文本:
\u03bc\u03b5 Some English Text \ud83d\ude9b\n#SomeHashTag
\ud83d\ude9b\翻譯成這個表情符號:??
正如這里所說:https ://python-list.python.narkive.com/aKjK4Jje/encoding-of-surrogate-code-points-to-utf-8
The definition of UTF-8 prohibits encoding character numbers
between U D800 and U DFFF, which are reserved for use with the
UTF-16 encoding form (as surrogate pairs) and do not directly
represent characters.
PostgreSQL 有以下編碼:
- 默認值:UTF8
- 整理:en_US.utf8
- Ctype:en_US.utf8
這是一個utf8問題嗎?或特定于表情符號?這是 django 還是 postgresql 問題?
uj5u.com熱心網友回復:
重現問題:
x='\u03bc\u03b5 Some English Text \ud83d\ude9b\n#SomeHashTag'
print(x)
Traceback(最近一次呼叫最后一次):檔案“”,第 1 行,在 UnicodeEncodeError:'utf-8' 編解碼器無法編碼位置 21-22 中的字符:不允許代理
解決方案:應用raw_unicode_escape和unicode_escape編解碼器(請參閱Python 特定編碼)如下:
y = x.encode('raw_unicode_escape').decode('unicode_escape').encode('utf-16_BE','surrogatepass').decode('utf-16_BE')
print(y)
με Some English Text ?? #SomeHashTag
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446071.html
標籤:Python django PostgreSQL 统一码 表情符号
