【问题标题】:Top 20 values from Counter in PythonPython 中 Counter 的前 20 个值
【发布时间】:2013-04-24 15:40:18
【问题描述】:

我的问题与我之前的问题类似:Python list help (incrementing count, appending)。我接受的答案效果很好。不过,这次我有一个不同的问题。

我正在从 json 文件中解析一个字符串,进行一些清理然后将其附加一个新字符串。我需要获取每个单词的计数器(这使它成为一个唯一的列表,出现的计数器被更新),按从高到低排序(我相信我需要在这里使用 most_common)然后将列表限制为 20。我可以所有这些都在 JavaScript 中完成,而不是在 python 中。

详细来说,我再次运行一个 for 循环,以像这样从字符串(json 字符串文件)中获取每个字符串。

# Counter for each word.
words = Counter();

for e in strings:
    # I am cleaning up the string here for unwanted chars, make it lower case
    # and append it to a new string variable.
    # if I were to print the new string variable it will look like this: 
    # hello test another test append hi hai hello hello

# i know I need to call words.update
# should I run a for loop in my new string variable  for each word?

还有我如何将其限制为 20?

我想要生成的是这样的:

word, count
hello 3
test 2
another 1
append 1
hai 1
hi 1

任何建议都会非常感谢。

【问题讨论】:

    标签: python counter


    【解决方案1】:

    如果你有一个单词的列表,你会使用.update() 方法:

    words.update(some_list_of_words)
    

    你也可以传入一个生成器表达式:

    words.update(word.lower() for word in e.split())
    

    会将字符串 e 拆分为空格上的单独单词,然后将每个单词小写并计算这些单词。

    .most_common()带一个参数,返回的最大项数:

    words.most_common(20)
    

    使用较少的单词进行演示,将其限制为最常用的前 3 个单词:

    >>> from collections import Counter
    >>> words = Counter('spam ham eggs baz foo bar baz spam ham eggs spam spam bacon eggs ham spam spam spam eggs ham'.split())
    >>> words.most_common(3)
    [('spam', 7), ('ham', 4), ('eggs', 4)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2015-06-27
      相关资源
      最近更新 更多