Vertical Histogram in Python
I'm trying to put text in to a vertical histogram using the length of words and the fre开发者_运维百科quency of those lengths as variables. I can do it easily horizontally, but I'm totally lost when it comes to going vertical. (yes, new to Python and programming in general)
I only want to use built-in modules for Python 3
Here's what I have so far (example text provided because I'm pulling from a file):
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))))
Here you go:
#!/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('')
精彩评论