gpt4 book ai didi

python - 如何在python中打印Counter的前十个元素

转载 作者:太空狗 更新时间:2023-10-30 00:34:17 32 4
gpt4 key购买 nike

使用这段代码,我打印了所有元素,这些元素首先按照文本文件中最常用的单词排序。但是我如何打印前十个元素?

with open("something.txt") as f:
words = Counter(f.read().split())
print(words)

最佳答案

来自文档:

most_common([n])

Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

我会尝试:

words = Counter(f.read().split()).most_common(10)

来源:here

关于python - 如何在python中打印Counter的前十个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46692352/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com