python - Python 中的表情符号

标签 python emoji

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

String to translate: Smile! You're too cool.

Translation: 😀! You're too 😎.

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

UnicodeEncodeError: 'UCS-2' codec can't encode character '\U0001f40d' in position 0: Non-BMP character not supported in Tk

有什么建议吗? 提前致谢

最佳答案

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 🆒.

关于python - Python 中的表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52158931/

相关文章:

c++ - 带有抽象类的 Python ctypes

iphone - 当 NSString 包含表情符号时如何获取 NSString 大小?

python - 为什么 readlines() 读取的内容比 sizehint 多得多?

python - 以时间间隔自动将日志从 CloudWatch 导出到 S3 存储桶

python - "... object is not iterable"是 "x in y"的误导性错误吗?

php - 如何在Android中使用PHP从数据库MySQL获取表情符号

javascript - 如何从 JavaScript 中的表情符号中获取真正的字符代码?

linux - 为什么 Shift+Ctrl+e 会导致 e 下划线并开始表情符号输入(linux)?

ruby - 如何打印 unicode 字符 U-1F4A9 'pile of poo' 表情符号

python - 属性错误: module "sklearn.utils" has no attribute "_joblib" when inheriting class `sklearn.ensemble.BaggingClassifier.`