原文鏈接:在這里
最近在對照著nltk.book學(xué)習(xí)NLTK庫捺萌,雖然網(wǎng)絡(luò)上有中文翻譯版丧裁,但是似乎并沒有搭配Python3的譯本,所以還是想按照自己的理解敲一遍浑厚,并且將文檔中介紹Python基礎(chǔ)操作的內(nèi)容刪去试读,只保留介紹NLTK庫的內(nèi)容杠纵,以方便后期使用時查閱和復(fù)習(xí)。
如果我有理解錯誤了的地方钩骇,非常歡迎大家留言指出!
Language Processing and Pyhton
import
impot
nltk
庫是常規(guī)用法比藻,我們使用from nltk.book import text1
來載入特定的文本。但是一個好玩的事情是倘屹,即使我們指定了特定的文本银亲,系統(tǒng)也會先輸出book中的文本目錄,看著就會很累纽匙。所以可以直接在lib
里將book.py
中的例行print
都注釋掉务蝠。
Searching Text
concotdance
concotance
可以讓我們在特定的文本中搜索特定的詞匯。 concotance
函數(shù)可以插入三個值烛缔,word
,width
,lines
馏段,word
是待檢索詞匯,width
是以待搜索詞為中心向兩邊擴(kuò)展開的長度践瓷,lines
可以輸出指定的結(jié)果行數(shù)院喜。
from nltk.book import text1
text1.concotdance('man',width = 10,lines = 3)
similar
similar
用來搜索文本中語義相近的詞匯。
common_contexts
common_contexts
用來搜索相似的詞的共現(xiàn)文本(一般在使用了similar
函數(shù)之后進(jìn)行個例對比)晕翠。
dispersion_plot
dispersion_plot
可以直觀地顯示特定詞在文章整體中大體的分布位置喷舀。前提是要裝好NumPy
和Matplotlib
庫(更推薦是下Python的時候就直接下好Anocanda,里面包含很多數(shù)據(jù)處理所需的庫)淋肾。
from nltk.book import text4
print(text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"]))
Counting Vocabulary
len()
直接使用len()
函數(shù)來測量文本總單詞數(shù)硫麻,但是如果想要去除掉重復(fù)的單詞和標(biāo)點(diǎn)符號就要改變一下。
from nltk.book import text6
from string import puncuation
a = sorted(set(text6))
b = [for i in a if i not in puncuation]
print(len(b))
lexical richness
len(set(text6))/len(text6)
count a specific word
text6.count('smoke')
lexical_diversity()
python其實(shí)也內(nèi)置了一個計(jì)算文本richness的函數(shù)lexical_diversity()
樊卓,只需要傳入需要分析的文本就可以拿愧。
而如果要計(jì)算某個特定的單詞在文本中的占比也可以直接用函數(shù)percentage()
函數(shù),輸入兩個值count
(出現(xiàn)次數(shù))和total
(樣本總數(shù))碌尔。
lexical_diversity(text3)
percentage(4,5)
percentage(text.count('a'),len(text4))
Frequency Distributions
FreqDist()
FreqDist()
函數(shù)會創(chuàng)建若干個字符-字符在文本中出現(xiàn)次數(shù)的一個元組浇辜,但是它自身是內(nèi)部函數(shù)自己定義的一個類,如果要使用七扰,需要再調(diào)用內(nèi)部的函數(shù)。
# 求最高頻的50個詞
from nltk.book import *
fdist = FreqDist(text1)
fdist.most_common(50)
# 還可以制圖(遞增順序)
print(fdist.plot(50,cumulative = true))
Collocations and Bigrams
collcations
是一個出現(xiàn)頻率較高的詞組陪白。
bigrams()
是用來將列表中的元素按照順序進(jìn)行二元組合颈走。bigrams
是NLTK
庫自定義的一個類,所以想要輸出需要轉(zhuǎn)化類型輸出咱士。collecations
本質(zhì)上就是bigrams()
在文本范圍內(nèi)的應(yīng)用立由,除非我們要關(guān)注那些少數(shù)搭配轧钓。
print(list(bigrams(['more', 'is', 'said', 'than', 'done'])))
# 運(yùn)行結(jié)果:[('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')]
text4.collocations()
# 運(yùn)行結(jié)果:United States; fellow citizens; four years; years ago; FederalGovernment; General Government; American people; Vice President; OldWorld; Almighty God; Fellow citizens; Chief Magistrate; Chief Justice;God bless; every citizen; Indian tribes; public debt; one another;foreign nations; political parties
補(bǔ)充函數(shù)
參考資料