【问题标题】:Counter for words and emoji文字和表情符号计数器
【发布时间】:2017-11-19 10:07:28
【问题描述】:

我有一个包含“clear_message”列的数据框,我创建了一个列来计算每行中的所有单词。

history['word_count'] = history.clear_message.apply(lambda x: Counter(x.split(' ')))

例如,如果行消息是:Hello my name is Hello 然后他所在行的计数器将是Counter({'Hello': 2, 'is': 1, 'my': 1, 'name': 1})

问题

我的文字中有表情符号,我还想要一个表情符号计数器。

例如:

test = '????????????????????here sasdsa'
test_counter = Counter(test.split(' '))

输出是:

Counter({'sasdsa': 1, '????????????????????here': 1})

但我想要:

Counter({'sasdsa': 1, '????': 5, 'here':1})

显然问题在于我使用的是split(' ')

我的想法:

在表情符号前后添加一个空格。喜欢:

test = '???? ???? ???? ???? ???? here sasdsa'

然后使用拆分,这将起作用。

  1. 不确定这种方法是否最好。
  2. 不知道该怎么做。 (我知道如果i 是一个表情符号,那么if i in emoji.UNICODE_EMOJI 将返回true(emoji 包)。

【问题讨论】:

    标签: python string pandas counter emoji


    【解决方案1】:

    我认为您在每个表情符号后添加空格的想法是一个好方法。如果表情符号和下一个字符之间已经有空格,您还需要去除空格,但这很简单。比如:

    def emoji_splitter(text):
        new_string = ""
        for char in text:
            if char in emoji.UNICODE_EMOJI:
                new_string += " {} ".format(char)
            else:
                new_string += char
        return [v for v in map(lambda x: x.strip(), new_string.split(" ")) if v != ""]
    

    也许您可以通过使用滑动窗口检查表情符号后的空格并仅在必要时添加空格来改进这一点,但这会假设永远只有一个空格,因为此解决方案应考虑 0 到 n 之间的空格表情符号。

    【讨论】:

    • 这段代码有一些问题,比如计数'' 和第一个表情符号之前没有空格。我添加了一些东西,并将其发布在这里作为答案。告诉我你的想法。谢谢:)
    【解决方案2】:

    @con-- 答案有一些问题,所以我修复了它。

    def emoji_splitter(text):
        new_string = ""
        text = text.lstrip()
        if text:
            new_string += text[0] + " "
        for char in ' '.join(text[1:].split()):
            new_string += char
            if char in emoji.UNICODE_EMOJI:
                new_string = new_string + " " 
        return list(map(lambda x: x.strip(), new_string.split()))
    

    示例:

    emoji_splitter(' a??? ads')
    Out[7]: ['a', '?', '?', '?', 'ads']
    

    【讨论】:

    • 好收获!我确实错过了在第一个表情符号之前没有空格的情况。但是,我认为您的解决方案也不能完全解决它。例如,如果您尝试emoji_splitter('aa??? ads'),您的代码应该返回['a', 'a?', '?', '?', 'ads'],因为您在第一个和第二个字符之间插入了一个空格,而不是第一个表情符号。我已经编辑了我的答案,我想我现在已经考虑了所有情况,将所有表情符号括在空格中,分割空格,然后删除列表中剩余的任何空字符串。
    猜你喜欢
    • 2016-01-10
    • 2017-12-27
    • 2017-03-14
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2014-08-06
    • 2023-03-03
    • 2020-05-20
    相关资源
    最近更新 更多