从字符串中提取所有表情符号并忽略 Python 中的 Fitzpatrick 修饰符(肤色等)

Extract all Emojis from string and ignore Fitzpatrick modifiers (skin tones etc.) in Python

我最近遇到了一个问题,我需要提取一个字符串中的所有表情符号来计算特定表情符号的出现次数。 Emoji python package let me extract all Emojis, but I always got specific modifiers such as Skin tones extracted as separate Emojis. I wanted to ignore Skin tones and other Fitzpatrick modifiers Variant Selectors (see this page for types and background on Fitzpatrick from Wikpedia)。以下代码将导致选择 Fitzpatrick 修饰符作为单独的表情符号(这不是我需要的):

import emoji
def extract_emojis(str):
  return list(c for c in str if c in emoji.UNICODE_EMOJI)

示例:这个表情符号 ❤️ 实际上由两部分组成,一颗心(Unicode 代码点:U+2764)和一个红色修饰符(Unicode 代码点:U+fe0f)。 print(repr('❤️')) 结果: \u2764\ufe0f - 两个独立的 unicode 但只有一个表情符号。单独的第二个代码点本身没有意义,但它作为单独的表情符号返回 return list(c for c in str if c in emoji.UNICODE_EMOJI).

列表中

这是一种忽略肤色和其他修饰符并将所有这些表情符号变体视为一个表情符号的解决方案。来自 Martijn Pieters 的 帮助为我的问题编写了以下解决方案:

import emoji
import unicodedata

def checkEmojiType(strEmo):
    if unicodedata.name(strEmo).startswith("EMOJI MODIFIER"):
        return False
    else:
        return True
def extract_emojis(str):
    return list(c for c in str if c in emoji.UNICODE_EMOJI and checkEmojiType(c))

[编辑] 然而..目前,上面的解决方案似乎不支持零宽度连接器(见下面的评论)。您可以使用以下代码自行测试:

n = '‍⚕️' #copy the medical emoji with zero-width joiner (http://www.unicode.org/emoji/charts/emoji-zwj-sequences.html). This should only fall back to a double-emoji if not otherwise available
#extract all emojis with the function from above
nlist = def_functions.extract_emojis(n)
for xstr in nlist:
    #print codepoints
    print('Emoji Extract: U+%04x' % ord(xstr))
for _c in n:
    #print all Unicode Codepoints directly
    print('Each Codepoint: U+%04x' % ord(_c))

这是输出:

EmojiExtract: U+1f468
EmojiExtract: U+2695
Each Codepoint: U+1f468
Each Codepoint: U+200d
Each Codepoint: U+2695
Each Codepoint: U+fe0f

Emoji Extract 没有加入这两个 Emoji(这是意料之中的)。