【问题标题】:Split and count emojis and words in a given string in Python在 Python 中对给定字符串中的表情符号和单词进行拆分和计数
【发布时间】:2018-08-13 07:29:04
【问题描述】:

对于给定的字符串,我正在尝试计算每个单词和表情符号的出现次数。对于仅包含 1 个表情符号的表情符号,我已经做到了 here。问题是当前的许多表情符号都是由几个表情符号组成的。

喜欢表情符号??????‍??????‍??????‍????由四个表情符号组成 - ??????‍ ????‍ ????‍ ????,以及具有人类肤色的表情符号,例如????????是 ???? ???等等。

问题归结为如何以正确的顺序拆分字符串,然后计算它们很容易。

有一些很好的问题解决了同样的问题,例如 link1link2 ,但它们都不适用于通用解决方案(或者解决方案已过时,或者我无法弄清楚)。

例如,如果字符串是hello ????????‍???? emoji hello ????‍????‍????‍????,那么我将拥有{'hello':2, 'emoji':1, '????‍????‍????‍????':1, '????????‍????':1} 我的字符串来自 Whatsapp,并且都是用 utf8 编码的。

我有很多糟糕的尝试。帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x unicode counter emoji


    【解决方案1】:

    emoji.UNICODE_EMOJI 是一个有结构的字典

    {'en': 
        {'?': ':1st_place_medal:',
         '?': ':2nd_place_medal:',
         '?': ':3rd_place_medal:' 
    ... }
    }
    

    因此您需要使用emoji.UNICODE_EMOJI['en'] 才能使上述代码正常工作。

    【讨论】:

      【解决方案2】:

      非常感谢Mark Tolonen。现在为了计算给定字符串中的单词和表情符号以及单词,我将使用emoji.UNICOME_EMOJI 来确定什么是表情符号,什么不是(来自emoji 包),然后从字符串中删除表情符号。

      目前不是一个理想的答案,但它可以工作,如果它会改变,我会编辑。

      import emoji
      import regex
      def split_count(text):
          total_emoji = []
          data = regex.findall(r'\X',text)
          flag = False
          for word in data:
              if any(char in emoji.UNICODE_EMOJI for char in word):  
                  total_emoji += [word] # total_emoji is a list of all emojis
      
          # Remove from the given text the emojis
          for current in total_emoji:
              text = text.replace(current, '') 
      
          return Counter(text.split() + total_emoji)
      
      
      text_string = "?????here hello world hello?‍?‍?‍???"    
      final_counter = split_count(text_string)
      

      输出:

      final_counter
      Counter({'hello': 2,
               'here': 1,
               'world': 1,
               '?\u200d?\u200d?\u200d?': 1,
               '?': 5,
               '??': 1})
      

      【讨论】:

        【解决方案3】:

        使用第 3 方 regex 模块,该模块支持识别字素簇(将 Unicode 代码点序列呈现为单个字符):

        >>> import regex
        >>> s='?‍?‍?‍???'
        >>> regex.findall(r'\X',s)
        ['?\u200d?\u200d?\u200d?', '??']
        >>> for c in regex.findall('\X',s):
        ...     print(c)
        ... 
        ?‍?‍?‍?
        ??
        

        计算它们:

        >>> data = regex.findall(r'\X',s)
        >>> from collections import Counter
        >>> Counter(data)
        Counter({'?\u200d?\u200d?\u200d?': 1, '??': 1})
        

        【讨论】:

        • 谢谢。当我在这个字符串中包含文本时应该怎么做?因为当字符串中有单词时,它也会计算所有的字母。
        • @sheldonzy 这更难,因为如您所见,表情符号很复杂,并且不是由 Unicode 表情符号范围内的严格代码点组成。
        • 好的,谢谢。我添加了完整的功能作为附加答案。不确定这是不是最好的作品,但目前可以。
        猜你喜欢
        • 1970-01-01
        • 2020-02-14
        • 2018-09-28
        • 2010-09-26
        • 2020-07-18
        • 1970-01-01
        • 2016-01-12
        相关资源
        最近更新 更多