gpt4 book ai didi

python - 将一串表情符号拆分为单个表情符号字符

转载 作者:行者123 更新时间:2023-11-30 23:05:27 25 4
gpt4 key购买 nike

假设我有以下字符串:DATA = "🚀😘👍🏾🇦🇮"

我想获取一个数组或列表,其中每个表情符号作为一个元素,就像这样 [🚀,😘,👍🏾,🇦🇮]

然而,问题在于表情符号的长度各不相同。所以 len(u'😘')1,而 len(u'👍🏾') 是 2。

那么我将如何分割我的DATA?我已经看到它是用 JavaScript 完成的,但无法找到在 Python 中完成的方法( How can I split a string containing emoji into an array? )。

最佳答案

使用第 3 方 regex 模块 (pip install regex) 和 Python 3.5:

>>> import regex
>>> s = '\U0001f680\U0001f618\U0001f44d\U0001f3fe\U0001f1e6\U0001f1ee'
>>> import unicodedata as ud
>>> ud.category(s[0])
'So'
>>> ud.category(s[1])
'So'
>>> ud.category(s[2])
'So'
>>> ud.category(s[3])
'Sk'
>>> ud.category(s[4])
'So'
>>> ud.category(s[5])
'So'
>>> regex.findall(r'\p{So}\p{Sk}*',s)
['\U0001f680', '\U0001f618', '\U0001f44d\U0001f3fe', '\U0001f1e6', '\U0001f1ee']

编辑:

国旗是两个字母的区域指示符号,范围为 U+1F1E6 - U+1F1FF。事实证明,regex 有一个字素簇 \X 开关,但它找到了标志,但没有找到肤色标记。

>>> regex.findall(r'\X',s)
['\U0001f680', '\U0001f618', '\U0001f44d', '\U0001f3fe', '\U0001f1e6\U0001f1ee']

但是,您可以查找符号修饰符或字素簇:

>>> regex.findall(r'.\p{Sk}+|\X',s)
['\U0001f680', '\U0001f618', '\U0001f44d\U0001f3fe', '\U0001f1e6\U0001f1ee']

可能还有其他异常(exception)。

关于python - 将一串表情符号拆分为单个表情符号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33130925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com