使用 collections.Counter 统计不同颜色的表情符号

Using collections.Counter to count emojis with different colors

我想使用 collections.Counter class 来计算字符串中的表情符号。它通常工作正常,但是,当我引入彩色表情符号时,表情符号的颜色分量与表情符号分开,如下所示:

>>> import collections
>>> emoji_string = ""
>>> emoji_counter = collections.Counter(emoji_string)
>>> emoji_counter.most_common()
[('', 5), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1)]

我怎样才能使 most_common() 函数 return 变成这样:

[('', 1), ('', 1), ('', 1), ('', 1), ('', 1)]

我正在使用 Python 3.6

您必须将字符串拆分成单独的簇。您的每个表情符号都是 两个代码点;表情符号和 EMOJI MODIFIER FITZPATRICK TYPE X 代码点:

>>> print(emoji_string[0])

>>> print(emoji_string[1])

>>> print(emoji_string[:2])

>>> print(ascii(emoji_string[:2]))
'\U0001f44c\U0001f3fb'
>>> import unicodedata
>>> unicodedata.name(emoji_string[1])
'EMOJI MODIFIER FITZPATRICK TYPE-1-2'

您可以使用正则表达式来保留前面的表情符号:

import re

char_with_modifier = re.compile(r'(.[\U0001f3fb-\U0001f3ff]?)')
split_emoji = char_with_modifier.findall(emoji_string)

并计算结果。

演示:

>>> import re
>>> from collections import Counter
>>> emoji_string = ""
>>> char_with_modifier = re.compile(r'(.[\U0001f3fb-\U0001f3ff]?)')
>>> Counter(char_with_modifier.findall(emoji_string))
Counter({'': 1, '': 1, '': 1, '': 1, '': 1})
import regex
from collections import Counter
emoji_string = ""
data = regex.findall(r'\X',emoji_string)
print(Counter(data))

预期产出

Counter({'': 1, '': 1, '': 1, '': 1, '': 1})