1

这就是我现在所拥有的,这要感谢 Pavel Anossov。我正在尝试将已输出的词频转换为星号。

import sys
import operator 
from collections import Counter
def candidateWord():


   with open("sample.txt", 'r') as f:
      text = f.read()
   words = [w.strip('!,.?1234567890-=@#$%^&*()_+')for w in text.lower().split()]
            #word_count[words] = word_count.get(words,0) + 1
   counter = Counter(words)

   print("\n".join("{} {}".format(*p) for p in counter.most_common()))

candidateWord()

这就是我现在所拥有的输出。

how 3

i 2

am 2

are 2

you 2

good 1

hbjkdfd 1

我想尝试使用的公式是最常见的单词出现 M 次,当前单词出现 N 次,打印的星号数为:

(50 * N) / M
4

2 回答 2

0

我将星号放在左边以避免对齐单词:

...
counter = Counter(words)
max_freq = counter.most_common()[0][1]
for word, freq in sorted(counter.most_common(), key=lambda p: (-p[1], p[0])):
    number_of_asterisks = (50 * freq ) // max_freq     # (50 * N) / M
    asterisks = '*' * number_of_asterisks        # the (50*N)/M asterisks
    print('{:>50} {}'.format(asterisks, word))

格式字符串的意思是“空格到 50 个字符的:>50左填充”。

  • counter.most_common返回(单词,频率)对的列表,按频率排序
  • counter.most_common()[0][1]如果第一对的第二个元素,那么最大频率
  • 我们counter.most_common()首先按频率降序进行循环,然后是单词
  • number_of_asterisks由您的公式计算得出。我们使用整数除法//得到整数结果。
  • 我们重复一个星号number_of_asterisks时间并将结果存储在asterisks
  • 我们打印asterisksword. 星号在 50 个字符宽的列中右对齐。
于 2013-03-31T22:45:39.547 回答
0

编码:

import sys
import operator 
from collections import Counter
def candidateWord():
   with open("sample.txt", 'r') as f:
      text = f.read()
   words = [w.strip('!,.?1234567890-=@#$%^&*()_+')for w in text.lower().split()]
            #word_count[words] = word_count.get(words,0) + 1
   counter = Counter(words)

   # I added the code below...
   columns = 80
   n_occurrences = 10
   to_plot = counter.most_common(n_occurrences)
   labels, values = zip(*to_plot)
   label_width = max(map(len, labels))
   data_width = columns - label_width - 1
   plot_format = '{:%d}|{:%d}' % (label_width, data_width)
   max_value = float(max(values))
   for i in range(len(labels)):
     v = int(values[i]/max_value*data_width)
     print(plot_format.format(labels[i], '*'*v))

candidateWord()

输出:

the |***************************************************************************
and |**********************************************                             
of  |******************************************                                 
to  |***************************                                                
a   |************************                                                   
in  |********************                                                       
that|******************                                                         
i   |****************                                                           
was |*************                                                              
it  |**********                                                                 
于 2013-03-31T22:46:02.930 回答