使用字典将表情符号替换为文本



我有一本名为emoji的词典,其中包含表情符号和含义。

{'  ': 'excited',  '  ': 'laugh',  '  ' : 'cry'}

并且我有一个被称为CCD_ 2的字符串作为输入。我试着翻译这条推文;我太激动了"使用下面的这个函数。

def replace_emoji(tweet):
return ' '.join(emoji.get(x, x) for x in tweet.split())

但如果表情符号之间没有这样的空间,那就不起作用了&";。所以我得到的输出和输入是一样的。有人能帮我解决这个问题吗?

与上面的注释类似,问题是split不适用于空字符串。我的建议是将列表理解替换为一个循环,该循环对每个字符进行迭代,如果表情符号出现在emojidict:中,则添加该字符或其翻译

def replace_emoji(tweet):
result = ''
for char in tweet:
result += emoji.get(char, char)
return result

在您的解决方案风格中,您还可以将split替换为将字符串强制转换为列表,而不是在' '上加入,您可以在''上加入以成功重新加入推文:

def replace_emoji(tweet):
return ''.join(emoji.get(x, x) for x in list(tweet))

使用split()将是对字符串进行拆分的最Python的方式。

记住,如果您对没有空格的字符串使用split(),那么字符串将在列表中返回给您,这也很有用。

示例:

>>> "      ".split()
['    ']
>>> "        ".split()
['  ','  ']

如果你使用列表,那么就有问题了,每个转换成字符的单词和表情符号都会保持原样,没有带空格,这是不好的。

代码:-

def replace_emoji(tweet):
return ''.join(emoji.get(x, x) for x in list(tweet))
print(replace_emoji("If you're a programmer   and blocks of text are needed          "))

输出:-如果你是一个程序员,需要大量文本最佳解决方案:

你可以尝试使用这个表情符号包。它主要用于将转义序列转换为unicode表情符号,但因此它包含了一个最新的表情列表。代码:-

from emoji import UNICODE_EMOJI
def is_emoji(s):
return s in UNICODE_EMOJI
emoji={'  ': 'excited',  '  ': 'laugh',  '  ' : 'cry'}
def replace_emoji(tweet):
result = ' '
for char in tweet:
if is_emoji(char):
result = result + ' ' + emoji.get(char, char)
else:
result += emoji.get(char, char)
return result
print(replace_emoji("If you're a programmer   and blocks of text are needed          "))

输出:如果你是一个程序员,需要大笑和文本块哭泣兴奋兴奋兴奋

最新更新