【问题标题】:Only print specific amount of Counter items, with decent formatting仅打印特定数量的 Counter 项目,格式良好
【发布时间】:2016-05-12 21:24:00
【问题描述】:

试图打印出文本文件中前 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 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 个最常用的单词,以及它们的数量。 单词:Blah 出现次数:3 词:bloo 出现次数:2 词:blee 出现次数:1

【问题讨论】:

    标签: python python-3.x counter


    【解决方案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”硬编码到您的代码中。

    【讨论】:

      【解决方案2】:

      保存最常见的元素并使用循环。

      common = word_counts.most_common(num)[0]
      for i in range(3):
          print("WORD: %s \nOCCURENCE: %d \n" % (common[i][0], common[i][1]))
      

      【讨论】:

      • 非常感谢!只是出于某种原因无法弄清楚我脑海中的系统。现在完美运行。
      • 如果有人可以解释反对意见,我很乐意改进这个答案(虽然我不确定如何 - 它已经解决了 OP 的问题)。
      • 不确定谁投了反对票,但由于这个答案是有效的 - 我正在用我的投票来平衡它;)
      猜你喜欢
      • 2012-05-22
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      相关资源
      最近更新 更多