簡體   English   中英

在Python 3中刪除BMP(表情符號)之外的字符

[英]Remove characters outside of the BMP (emoji's) in Python 3

我有一個錯誤: UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 266-266: Non-BMP character not supported in Tk

我正在解析數據,然后將一些表情符號分解為數組。 data = 'this variable contains some emoji'sツ😂'我想: data = 'this variable contains some emoji's'

如何從數據中刪除這些字符或在Python 3中處理這種情況?

如果目標只是刪除'\￿'以上'\￿'所有字符,那么直接的方法就是這樣做:

data = "this variable contains some emoji'sツ😂"
data = ''.join(c for c in data if c <= '\uFFFF')

您的字符串可能是分解形式的,因此您可能需要先將normalize為組合形式,以便可以識別非BMP字符:

import unicodedata

data = ''.join(c for c in unicodedata.normalize('NFC', data) if c <= '\uFFFF')
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, data)
"this variable contains some emoji's"

對於BMP,請閱讀以下內容: 從Python中的字符串中刪除表情符號

暫無
暫無

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

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