【问题标题】:Filter words only instead of punctuations仅过滤单词而不是标点符号
【发布时间】:2021-02-14 04:43:09
【问题描述】:

我正在尝试浏览正面 ('pos') 和负面 ('neg') 列表。这里的问题是下面的脚本也包括了空格和标点符号,我不希望这样。我只想从这些列表中提取最常见的 30 个单词。知道如何做到这一点吗?

#for counting frequently occurrence of negative and positive words.

from collections import Counter

count1 = Counter(" ".join(data[data['sentiment']=='pos']["text"]).split()).most_common(30)
data1 = pd.DataFrame.from_dict(count1)
data1 = data1.rename(columns={0: "words of positive", 1 : "count"})
count2 = Counter(" ".join(data[data['sentiment']=='neg']["text"]).split()).most_common(30)
data2 = pd.DataFrame.from_dict(count2)
data2 = data2.rename(columns={0: "words of negative", 1 : "count_"})

编辑

上面的实现有正确的想法,但是我希望提取有意义的单词而不是逻辑连接词,例如 (the, and a it that) 以及标点符号

【问题讨论】:

  • 最简单的方法可能是使用 re.sub(r'[^\w\s]', '', my_string) 之类的东西预处理您的文本,这将删除所有标点符号

标签: python list find-occurrences


【解决方案1】:

您可以替换.split()

data[data['sentiment']=='pos']["text"]).split()

带有regex 函数

import re

def return_words(string):
    return re.findall(r'\b\S+\b', string.lower())

return_words(data[data['sentiment']=='pos']["text"]))

所以把它放在你的代码中:

from collections import Counter
import re

def return_words(string):
    return re.findall(r'\b\S+\b', string.lower())

count1 = Counter(" ".join(return_words(data[data['sentiment']=='pos']["text"]))).most_common(30)
data1 = pd.DataFrame.from_dict(count1)
data1 = data1.rename(columns={0: "words of positive", 1 : "count"})
count2 = Counter(" ".join(retrn_words(data[data['sentiment']=='neg']["text"]))).most_common(30)
data2 = pd.DataFrame.from_dict(count2)
data2 = data2.rename(columns={0: "words of negative", 1 : "count_"})

【讨论】:

  • AttributeError: 'Series' 对象没有属性 'lower'
  • @Polacan 也许试试string.str.lower()
  • TypeError: 预期的字符串或类似字节的对象
  • @Polacan str(string.str) 怎么样?
  • 输出显示我想到的最常用单词的第一个字母(即 t s a n ..)
猜你喜欢
  • 1970-01-01
  • 2021-03-29
  • 2018-02-27
  • 1970-01-01
  • 2021-07-27
  • 2016-01-05
  • 2019-06-02
  • 2012-09-03
  • 1970-01-01
相关资源
最近更新 更多