Collections.counter()正在计算字母而不是单词

2024-10-01 07:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须从数据帧的第df['messages']行中统计最多出现的单词数。它有许多列,所以我将所有行格式化并存储为单个字符串(单词按空格连接),存储在一个variabelall_wordsall_words所有单词都用空格分隔。但当我试着数一数最常用的单词时,它显示了我最常用的字母表。 我的数据格式如下:

0    abc de fghi klm
1    qwe sd fd s dsdd sswd??
3    ded fsf sfsdc wfecew wcw.

这是我的代码片段。

   from collections import Counter
    all_words = ' '
    for msg in df['messages'].values:
        words = str(msg).lower()
        all_words = all_words + str(words) + ' '
            
    count = Counter(all_words)
    count.most_common(3)

这是它的输出:

[(' ', 5260), ('a', 2919), ('h', 1557)]

我还尝试使用df['messages'].value_counts()。但它返回使用最多的行(整个句子)而不是单词。 比如:

asad adas asda     10
asaa as awe        3
wedxew dqwed       1

请告诉我哪里错了,或者建议其他可行的方法


Tags: 数据字符串dfcountcountermsgall单词
2条回答
from collections import Counter
all_words = []
for msg in df['messages'].values:
    words = str(msg).lower().strip().split(' ')
    all_words.extend(words)
            
count = Counter(all_words)
count.most_common(3)

计数器对传递给它的内容进行迭代。如果您向它传递一个字符串,它将进行迭代,因为它有个字符(这就是它的计数)。如果您向它传递一个列表(其中每个列表都是一个单词),它将按单词计数

from collections import Counter

text = "spam and more spam"

c = Counter()
c.update(text)  # text is a str, count chars
c
# Counter({'s': 2, 'p': 2, 'a': 3, 'm': 3, [...], 'e': 1})

c = Counter()
c.update(text.split())  # now is a list like: ['spam', 'and', 'more', 'spam']
c
# Counter({'spam': 2, 'and': 1, 'more': 1})

所以,你应该这样做:

from collections import Counter

all_words = []
for msg in df['messages'].values:
    words = str(msg).lower() 
    all_words.append(words)

count = Counter(all_words)
count.most_common(3)

# the same, but with  generator comprehension
count = Counter(str(msg).lower() for msg in df['messages'].values)

相关问题 更多 >