从文本中删除所有表情符号

FeF*_*Fum 4 python unicode-string python-3.x emoji python-unicode

这个问题在这里被问到Python : How to remove all emojis without a solution,我已经朝着解决方案迈出了一步。但需要帮助完成它。

我从表情符号网站上获取了所有表情符号十六进制代码点:https : //www.unicode.org/emoji/charts/emoji-ordering.txt

然后我像这样读入文件:

file = open('emoji-ordering.txt')
temp = file.readline()

final_list = []

while temp != '':
    #print(temp)
    if not temp[0] == '#' :
            utf_8_values = ((temp.split(';')[0]).rstrip()).split(' ')
            values = ["u\\"+(word[0]+((8 - len(word[2:]))*'0' + word[2:]).rstrip()) for word in utf_8_values]
            #print(values[0])
            final_list = final_list + values
    temp = file.readline()

print(final_list)
Run Code Online (Sandbox Code Playgroud)

我希望这会给我 unicode 文字。不是,我的目标是获得 unicode 文字,这样我就可以使用上一个问题的部分解决方案,并能够排除所有表情符号。任何想法我们需要什么才能获得解决方案?

小智 9

首先安装表情符号:

pip install emoji
Run Code Online (Sandbox Code Playgroud)

或者

pip3 install emoji
Run Code Online (Sandbox Code Playgroud)

所以这样做:

import emoji

def give_emoji_free_text(self, text):
    allchars = [str for str in text]
    emoji_list = [c for c in allchars if c in emoji.UNICODE_EMOJI]
    clean_text = ' '.join([str for str in text.split() if not any(i in str for i in emoji_list)])

    return clean_text

text = give_emoji_free_text(text)
Run Code Online (Sandbox Code Playgroud)

这对我有用!

或者你可以试试:

emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
        u"\U0001F1F2-\U0001F1F4"  # Macau flag
        u"\U0001F1E6-\U0001F1FF"  # flags
        u"\U0001F600-\U0001F64F"
        u"\U00002702-\U000027B0"
        u"\U000024C2-\U0001F251"
        u"\U0001f926-\U0001f937"
        u"\U0001F1F2"
        u"\U0001F1F4"
        u"\U0001F620"
        u"\u200d"
        u"\u2640-\u2642"
        "]+", flags=re.UNICODE)

text = emoji_pattern.sub(r'', text)
Run Code Online (Sandbox Code Playgroud)


jef*_*ale 5

这是一个使用 emoji 库的get_emoji_regexp().

它从文件中读取文本并将无表情符号的文本写入另一个文件。

import emoji
import re

def strip_emoji(text):
    print(emoji.emoji_count(text))
    new_text = re.sub(emoji.get_emoji_regexp(), r"", text)
    return new_text


with open("my_file.md", "r") as file:
    old_text = file.read()

no_emoji_text = strip_emoji(old_text)

with open("file.md", "w+") as new_file:
    new_file.write(no_emoji_text)
Run Code Online (Sandbox Code Playgroud)