0
!pip install emot
from emot.emo_unicode import EMOTICONS_EMO
def convert_emoticons(text):
    for emot in EMOTICONS_EMO:
        text = re.sub(u'\('+emot+'\)', "_".join(EMOTICONS_EMO[emot].replace(",","").split()), text)
        return text

text = "Hello :-) :-)"
convert_emoticons(text)

我试图在google collab中运行上面的代码,但它给出了以下错误:unbalanced parenthesis at position 4

我对 re 模块文档的理解告诉我这'\(any_expression'\)'是正确的使用方式,但我仍然得到错误。所以,我尝试替换'\(' + emot + '\)为:

  1. '(' + emot + ')',它给出了同样的错误
  2. '[' + emot + ']',它给出以下输出:Hello Happy_face_or_smiley-Happy_face_or_smiley Happy_face_or_smiley-Happy_face_or_smiley

正确的输出应该Hello Happy_face_smiley Happy_face_smileytext = "Hello :-) :-)"

有人可以帮我解决问题吗?

4

1 回答 1

0

使用正则表达式非常棘手,因为您首先需要转义表情符号中包含的正则表达式中的元字符,例如 :)和 : (,这就是您得到不平衡括号的原因。所以,你需要先做这样的事情:

>>> print(re.sub(r'([()...])', r'%s\1' % '\\\\', ':)'))
:\)

但我建议直接替换,因为您已经有一个正在迭代的映射。所以我们有:

from emot.emo_unicode import EMOTICONS_EMO
def convert_emoticons(text):
    for emot in EMOTICONS_EMO:
        text = text.replace(emot, EMOTICONS_EMO[emot].replace(" ","_"))
    return text


text = "Hello :-) :-)"
convert_emoticons(text)
# 'Hello Happy_face_smiley Happy_face_smiley'
于 2022-02-01T04:45:28.643 回答