Skip to main content
 首页 » 编程设计

python之NLTK:模态频率的条形图

2024年10月01日7shanyou

我是nltk初学者。最近,我在绘制模态频率条形图时遇到困难。

colors = 'rgbcmyk' 
def bar_chart(categories, words, counts): 
    import pylab 
    ind = pylab.arange(len(words)) 
    width = 1 / (len(categories) + 1) 
    bar_groups = [] 
    for c in range(len(categories)): 
        bars = pylab.bar(ind+c*width, counts[categories[c]], width,  
                         color=colors[c % len(colors)]) 
        bar_groups.append(bars) 
    pylab.xticks(ind+width, words) 
    pylab.legend([b[0] for b in bar_groups], categories, loc = 'upper left') 
    pylab.ylabel('Frequency') 
    pylab.title('Frequency of Six Modal Verbs by Genre') 
    pylab.show() 
 
import nltk 
from nltk.corpus import brown 
genres = ['news', 'religion', 'hobbies', 'government', 'adventure'] 
modals = ['can', 'could', 'may', 'might', 'must', 'will'] 
cfd = nltk.ConditionalFreqDist( 
        (genre, word) 
        for genre in brown.categories() 
        for word in brown.words(categories = genre) 
        if word in modals) 
counts = {} 
for genre in genres: 
    counts[genre] = [cfd[genre][word] for word in modals] 
bar_chart(genre, modals, counts) 

运行“bar_chart”函数后,Python 可以提供格式,但看不到柱状图。我怀疑是不是Python没有从brown读取数据,所以我用了:

cfd.tabulate(conditions = genres, samples = modals) 

输出:

             can could   may might  must  will  
      news    93    86    66    38    50   389  
  religion    82    59    78    12    54    71  
   hobbies   268    58   131    22    83   264  
government   117    38   153    13   102   244  
 adventure    46   151     5    58    27    50  

看来是Python读取了数据。我想确定错误在哪里。非常感谢。

请您参考如下方法:

我总是讨厌处理条形图,并尝试尽可能多地减少工作量。一种方法是使用 Pandas将数据加载为 DataFrame,然后使用其绘图界面(使用 matplotlib)创建条形图。

所以您可以去掉 bar_chart 函数并执行如下操作:

import pandas as pd 
 
df = pd.DataFrame(list(counts.values()), counts.keys(), modals) 
df.plot(kind='bar') 

话虽这么说,显示图像的麻烦实际上取决于你在什么环境中工作。如果你在 Jupyter 中,你可以使用魔法命令 %matplotlib inline 图像将会弹出在调用 plot 方法之后。如果您正在编写脚本并想保存图像,您可以这样做:

import matplotlib.pyplot as plt 
 
fig, ax = plt.subplots() 
df.plot(kind='bar', ax=ax) 
plt.tight_layout() 
plt.savefig('some file name.png') 

你应该得到这样的结果: