Python 仅打印特定数量的计数器项目,格式适当
试图打印出文本文件中前N个最常用的单词。到目前为止,我已经有了文件系统和计数器,所有的东西都在工作,只是不知道如何以一种漂亮的方式打印出我想要的数量。这是我的密码Python 仅打印特定数量的计数器项目,格式适当,python,python-3.x,counter,Python,Python 3.x,Counter,试图打印出文本文件中前N个最常用的单词。到目前为止,我已经有了文件系统和计数器,所有的东西都在工作,只是不知道如何以一种漂亮的方式打印出我想要的数量。这是我的密码 import re from collections import Counter def wordcount(user): """ Docstring for word count. """ file=input("Enter full file name w/ extension: ") num=int(input("Enter
import re
from collections import Counter
def wordcount(user):
"""
Docstring for word count.
"""
file=input("Enter full file name w/ extension: ")
num=int(input("Enter how many words you want displayed: "))
with open(file) as f:
text = f.read()
words = re.findall(r'\w+', text)
cap_words = [word.upper() for word in words]
word_counts = Counter(cap_words)
char, n = word_counts.most_common(num)[0]
print ("WORD: %s \nOCCURENCE: %d " % (char, n) + '\n')
基本上,我只想做一个循环,它会打印出以下内容
例如num=3
因此,它将打印出3个最常用的单词,以及它们的数量。
单词:废话发生率:3
单词:bloo发生率:2
单词:blee出现:1保存最常见的元素并使用循环
common = word_counts.most_common(num)[0]
for i in range(3):
print("WORD: %s \nOCCURENCE: %d \n" % (common[i][0], common[i][1]))
保存最常用的元素并使用循环
common = word_counts.most_common(num)[0]
for i in range(3):
print("WORD: %s \nOCCURENCE: %d \n" % (common[i][0], common[i][1]))
我将重复“最常见”如下:
most_common = word_counts.most_common(num) # removed the [0] since we're not looking only at the first item!
for item in most_common:
print("WORD: {} OCCURENCE: {}".format(item[0], item[1]))
两条评论:1.使用
format()
格式化字符串,而不是%
-稍后您将感谢我的建议2.这样,您就可以迭代任意数量的“top N”结果,而无需将“3”硬编码到代码中。我将迭代“最常见”结果,如下所示:
most_common = word_counts.most_common(num) # removed the [0] since we're not looking only at the first item!
for item in most_common:
print("WORD: {} OCCURENCE: {}".format(item[0], item[1]))
两条评论:1.使用
format()
格式化字符串,而不是%
-稍后您将感谢我的建议2.这样,您就可以迭代任意数量的“top N”结果,而无需在代码中硬编码“3”。非常感谢!只是因为某种原因,我无法在脑海中理解这个系统。现在效果很好。如果有人能解释否决票,我很想改进这个答案(虽然我不确定它是如何解决OP的问题的)。不确定谁否决了,但由于这个答案是有效的,我正在用我的投票来平衡它;)非常感谢!只是因为某种原因,我无法在脑海中理解这个系统。现在效果很好。如果有人能解释否决票,我很想改进这个答案(虽然我不确定它是如何解决OP的问题的)。不确定谁否决了,但由于这个答案是有效的,我正在用我的投票来平衡它;)