2011-03-24 123 views
0

我試圖將文本放入垂直直方圖中,使用單詞的長度和這些長度的頻率作爲變量。我可以很容易地做到這一點,但在垂直方向上我完全失去了。 (是的,新來的Python和通用編程)Python中的垂直直方圖

我只希望使用內置模塊爲Python 3

這裏是我到目前爲止(提供的示例文本,因爲我從拉文件):

import itertools 

text = "This is a sample text for this example to work." 
word_list = [] 
word_seq = [] 

text = text.strip() 

for punc in ".,;:!?'-&[]()" + '"' + '/': 
    text = text.replace(punc, "") 

words = text.lower().split() 

for word in words: 
    word_count = len(word) 
    word_list.append(word_count) 

word_list.sort() 

for key, iter in itertools.groupby(word_list): 
    word_seq.append((key, len(list(iter)))) 
+0

嘗試用簡單的2D名單(名單列表)這樣做。 – 2011-03-24 23:07:34

回答

1

在這裏你去:

#!/usr/bin/env python 
import fileinput 

freq = {} 
max_freq = 0 

for line in fileinput.input(): 
    length = len(line) 
    freq[length] = freq.get(length, 0) + 1 
    if freq[length] > max_freq: 
     max_freq = freq[length] 

for i in range(max_freq, -1, -1): 
    for length in sorted(freq.keys()): 
     if freq[length] >= i: 
      print('#', end='') 
     else: 
      print(' ', end='') 
    print('') 
+0

如何用數值打印軸? – 2011-06-22 12:34:46