Python中的垂直直方图

0 投票
1 回答
2753 浏览
提问于 2025-04-16 14:22

我正在尝试把文字放进一个竖着的柱状图里,使用单词的长度和这些长度出现的频率作为变量。我可以很容易地做成横着的,但对于竖着的完全不知道该怎么做。(是的,我对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))))

1 个回答

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('')

撰写回答