布朗语料库中不同部分的情态动词频率直方图绘制的代码详细解释
生活随笔
收集整理的這篇文章主要介紹了
布朗语料库中不同部分的情态动词频率直方图绘制的代码详细解释
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
《Python自然語言處理》P184
# -*- coding: utf-8 -*- import nltk colors='rgbcmyk' def bar_chart(categories,words,counts):"Plot a bar chart showing counts for each word by category"import pylabind=pylab.arange(len(words))#這里的words其實指的是情態(tài)動詞的個數(shù),對于本測試案例而言,ind=[0,1,2,3,4,5]print ("ind=",ind)width=1/(len(categories)+1)bar_groups=[]for c in range(len(categories)):print("typeof(c):",type(c))print("ind+c*width=",ind+c*width)#每個循環(huán)只畫一個文章種類中,各個情感動詞的頻次對應(yīng)的直方#ind+c*width表示當(dāng)前情感動詞在x軸上的具體位置bars=pylab.bar(ind+c*width,counts[categories[c]],width,color=colors[c%len(colors)])#counts[categories[c]]代表直方的高度bar_groups.append(bars)pylab.xticks(ind+width,words)#把坐標(biāo)橫軸從原本的[0,1,2,3,4,5]轉(zhuǎn)化為顯示成具體的英文單詞pylab.legend([b[0]for b in bar_groups],categories,loc='upper left')#繪制直方圖左上方的標(biāo)簽,告訴讀者,什么顏色對應(yīng)哪一類文本pylab.ylabel('Frequency')pylab.title('Frequency fo Six Modal Verbs by Genre')pylab.show()if __name__=='__main__':genres=['news','religion','hobbies','government','adventure']#表示文章屬于哪個類別modals=['can','could','may','might','must','will']#表示需要統(tǒng)計的情態(tài)動詞cfdist=nltk.ConditionalFreqDist((genre,word)for genre in genres for word in nltk.corpus.brown.words(categories=genre)if word in modals)#在word屬于modals列表的情況下#cfdist是個二維數(shù)組:cfdist[類別][情感動詞]#上面語句中的意思是,調(diào)用ConditionalFreqDist對nltk中的指定類別(genre)的語料進(jìn)行word頻次統(tǒng)計print("cfdist=",cfdist)counts={}for genre in genres: counts[genre]=[cfdist[genre][word] for word in modals] for genre in genres:for word in modals:print("cfdist[genre][word]=",cfdist[genre][word])#這個雙重for循環(huán)# 是在模仿上面的那個循環(huán),cfdist[genre][word]表示,genre類別中,word這個詞語粗線的頻率(也就是次數(shù))bar_chart(genres,modals,counts)
必須python3.x下運行,不能python2.x運行
總結(jié)
以上是生活随笔為你收集整理的布朗语料库中不同部分的情态动词频率直方图绘制的代码详细解释的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nltk断句
- 下一篇: AttributeError: modu