Python 生成基于文本的直方图

Python 生成基于文本的直方图,python,dictionary,histogram,Python,Dictionary,Histogram,我现在有一些代码,可以打印出文件中每个单词的频率。我如何修改它以生成显示每个单词的值百分比的直方图 from collections import Counter data = open( 'Test.txt' ).read() # read the file data = ''.join( [i.upper() if i.isalpha() else ' ' for i in data] ) # remove the punctuation c = Counter( data.split

我现在有一些代码,可以打印出文件中每个单词的频率。我如何修改它以生成显示每个单词的值百分比的直方图

from collections import Counter
data = open( 'Test.txt' ).read()  # read the file
data = ''.join( [i.upper() if i.isalpha() else ' ' for i in data] )   # remove the punctuation
c = Counter( data.split() )   # count the words
print(c)

使用听写理解和简单划分的简单方法:

c = Counter('abbccc')
s = sum(c.values())
perc = {k: v*100.0/s for k, v in c.items()}
# {'a': 16.666666666666668, 'b': 33.333333333333336, 'c': 50.0}

这个脚本创建了一个类似于您创建的字典,而不是字数,它将百分比作为一个值。希望这有帮助:)


python中有几个包允许您创建直方图。例如,bokeh、numpy或matplotlib您可以使用每个单词作为键,计数作为值来填充字典。这样,您就可以生成一个直方图。numpy和matplotlib确实提供了一些功能,但我认为您的问题是如何为这些选项提供输入,对吗?
from collections import Counter
data = open( 'test.txt' ).read()  # read the file
data = ''.join( [i.upper() if i.isalpha() else ' ' for i in data] )   # remove the punctuation
c = Counter( data.split() )   # count the words
print(c)

values_list = c.values()
word_sum = 0

for v in values_list:
    word_sum += v # get the number of words in the file

percent_dict = {}
for k, v in c.items():
    percentage = (100*v)/word_sum
    percent_dict[k] = percentage

    print(percent_dict)