0

我的问题与我之前的问题类似: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

任何建议都会非常感谢。

4

1 回答 1

3

如果您有单词列表.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)]
于 2013-04-24T15:42:26.153 回答