我正在尝试使用 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/