NLTK: bar chart for frequency of modals

Viewed 2005

I am a nltk beginner. Recently, I am facing difficulties when drawing a bar chart for frequency of modals.

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)

The format could be provided by Python after running the function 'bar_chart,' but the bar could not be seen. I suspected whether Python did not read the data from brown, so I used:

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

Output:

             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 

It seems that Python read the data. I want to ensure where the mistakes are. Thank you very much.

2 Answers
Related