文本文件中的频率和创建饼图

Frequencies in a text file and creating a pie chart

我有一个非常大的文本文件。我想分析它并绘制这些分析图。我所做的一项分析是找到 5 个最常见的词。

     f = open('story.txt','r')
        words = [x for y in [l.split() for l in f.readlines()] for x in y]
        data = sorted([(w, words.count(w)) for w in set(words)], key = lambda x:x[1], reverse=True)[:5] 

    print data

    most_words = [x[0] for x in data]
    times_used = [int(x[1]) for x in data]
    print most_words
    print times_used

显示这个:

[('the', 4826), ('of', 2276), ('and', 1825), ('a', 1761), ('to', 1693)]
['the', 'of', 'and', 'a', 'to']
[4826, 2276, 1825, 1761, 1693]

这么大的文件,需要花点时间分析。首先我想知道是否有更快的方法来做到这一点?其次,我想用这些数据创建一个饼图。我设法弄清楚如何用这些数据制作条形图,但制作饼图似乎让我望而却步。任何帮助都会很棒!

同样,如果有一种方法可以加快搜索大型文本文件的速度并且不会在过程中使用太多 RAM,我可以听到我的计算机 运行 的声音 运行这个。谢谢!

.. 或者,如果您认为有任何帖子可能有帮助,请告诉我,我已经搜索了一个多小时的问题解决方案,并决定提出我自己的问题以寻求帮助!

对于绘图部分,您可以使用以下方法完成:

import matplotlib.pyplot as plt

words = [('the', 4826), ('of', 2276), ('and', 1825), ('a', 1761), ('to', 1693)]
sizes, labels = [i[1] for i in words],[i[0] for i in words]
plt.pie(sizes, labels=labels,autopct='%1.1i%%')
plt.show()

,结果是:

您可以为颜色、爆炸等提供其他参数。检查 this matplotlib 演示。

对于性能部分,我建议你看一下这个 post:

Python program that finds most frequent word in a .txt file, Must print word and its count

@ninjagecko 解决方案在我看来可能更快,但您必须对其进行测试才能看到。