How to split emoji from each other python?

…衆ロ難τιáo~ 提交于 2019-12-14 00:37:28

问题


I need to split emoji from each other for example

EM = 'Hey 😷😷😷'
EM.split()

If we split it we will have

['Hey' ,'😷😷😷']

I want to have

['hey' , '😷' , '😷' , '😷']

and I want it to be applied to all emojis.


回答1:


You should be able to use get_emoji_regexp from the https://pypi.org/project/emoji/, together with the usual split function . So something like:

import functools
import operator
import re

import emoji

em = 'Hey 😷😷😷'
em_split_emoji = emoji.get_emoji_regexp().split(em)
em_split_whitespace = [substr.split() for substr in em_split_emoji]
em_split = functools.reduce(operator.concat, em_split_whitespace)

print(em_split)

outputs:

['Hey', '😷', '😷', '😷']

A more complex case, with family, skin tone modifiers, and a flag:

em = 'Hey 👨‍👩‍👧‍👧👨🏿😷😷🇬🇧'
em_split_emoji = emoji.get_emoji_regexp().split(em)
em_split_whitespace = [substr.split() for substr in em_split_emoji]
em_split = functools.reduce(operator.concat, em_split_whitespace)

for separated in em_split:
    print(separated)

outputs:

Hey
👨‍👩‍👧‍👧
👨🏿
😷
😷
🇬🇧

(I think something's up with using print on a list with the family emoji, hence printing each item of the list separately. Printing family emoji, with U+200D zero-width joiner, directly, vs via list)




回答2:


If the Emoji is 4 bytes, the first byte is hex Fx. Regexp: f[0-7]
If the Emoticon is 3 bytes, the first byte is hex Ex. e[0-9a-f]

This is where 'x' is some other hex digit.

Examples:

😁 is hex f0 9f 98 81
☺ is hex e2 98 ba

After the first hex byte, the other bytes are something that matches this regexp: [89ab][0-9a-f]




回答3:


Seems like emojis are 4 bytes long, you can simply cut your string every 4. Here's some code for you:

text = 'Hey \xf0\x9f\x98\xb7\xf0\x9f\x98\xb7\xf0\x9f\x98\xb7'

print text
print 'text.split()=%s' % text.split()

emojis_str = text.split()[1]
emojis_list = [emojis_str[i:i+4] for i in range(0, len(emojis_str), 4)]

print 'emojis_list=%s' % emojis_list

for em in emojis_list:
    print 'emoji: %s' % em

will output

$ python em.py
Hey 😷😷😷
text.split()=['Hey', '\xf0\x9f\x98\xb7\xf0\x9f\x98\xb7\xf0\x9f\x98\xb7']
emojis_list=['\xf0\x9f\x98\xb7', '\xf0\x9f\x98\xb7', '\xf0\x9f\x98\xb7']
emoji: 😷
emoji: 😷
emoji: 😷
$


来源:https://stackoverflow.com/questions/49921720/how-to-split-emoji-from-each-other-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!