【问题标题】:Emojis in PythonPython中的表情符号
【发布时间】:2018-09-04 04:44:33
【问题描述】:

我正在尝试使用 python 处理我的小项目(最近开始学习它),并且我正在尝试制作一个表情符号转换器。我的意思是,当文本包含表情符号时,转换器会将那个词变成表情符号。一个例子是:

要翻译的字符串:微笑!你太酷了。

翻译:????!你也是????。

问题是,我不知道从哪里开始,而且我尝试过的事情总是给我同样的错误:

UnicodeEncodeError:“UCS-2”编解码器无法编码字符“\U0001f40d” 在位置 0:Tk 中不支持非 BMP 字符

有什么建议吗? 提前致谢

【问题讨论】:

  • 您可以从unicodedata 模块开始。 unicodedata.name(character) 会给你一个角色的名字。例如。 unicodedata.name('????') -> 'GRINNING FACE'。您可以通过情感将表情符号组合在一起并构建一个文本 -> 表情符号翻译表。
  • 另见this相关问题。

标签: python emoji


【解决方案1】:

https://pypi.org/project/emoji/

没有太多文档,但您可以通过在 github https://github.com/carpedm20/emoji/search?q=emojize&unscoped_q=emojize 上探索获得一些想法

import emoji
import os
from string import punctuation

#example 1
string_to_translate1 = ":smile:! You're too :cool:."
translation1 = emoji.emojize(string_to_translate1,use_aliases=True,delimiters =(':',':'))

#example 2
string_to_translate2 = ":smile:! You're too :sunglasses:."
translation2 = emoji.emojize(string_to_translate2,use_aliases=True,delimiters =(':',':'))

#example 3
def custom_emojizer(user_text):
    temp_word_list = []

    for w in user_text.split():
        word = w
        endwith = ''
        for idx,char in enumerate(word):
            if char in punctuation:
                endwith = word[idx:]
                word = word.strip(char)
                break

        word_emoji = emoji.emojize(':'+word.lower()+':',use_aliases=True,delimiters =(':',':'))

        if ':' in word_emoji:
            temp_word_list.append(w)
        else:
            temp_word_list.append(word_emoji+endwith)

    return ' '.join(temp_word_list)


string_to_translate3 = "Smile! You're too cool."
translation3 = custom_emojizer(string_to_translate3)


with open('test.html','w+',encoding='utf-8-sig') as f:
    f.write(translation1+'<br>')
    f.write(translation2+'<br>')
    f.write(translation3)
os.startfile('test.html')

我们在 custom_emojizer 中做什么:

因为在你的 user_string '微笑!你太酷了。' 您在单词末尾有标点符号,单词可以是大写/标题大小写并且没有分隔符我们需要遍历 user_string 中的单词和 1)删除标点符号和 2)将单词转换为 lower() 和 3)在给 emoji.emojize 之前添加分隔符,然后如果单词成功转换为表情符号,我们将没有任何分隔符,我们需要做的就是添加标点符号(如果有),否则我们将添加原始单词。

输出:

?! You're too ?.
?! You're too ?.
?! You're too ?.

【讨论】:

  • 非常感谢。这给了我巨大的帮助来完成我想做的事情。 :)
  • @user484263 很高兴能帮上忙。
猜你喜欢
  • 2022-07-23
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 2020-10-22
相关资源
最近更新 更多