我的问题与我之前的问题类似: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
任何建议都会非常感谢。