NLTK以及相關包的安裝
安裝nltk包可以通過pip, 輸入:
pip install nltk
即可。之後,打開一個python環境,輸入:
import nltk
nltk.download()
在下列對話框中,選擇all,點擊Download,即可下載所有NLTK處理模塊。
下載完成後如圖所示:
導入自帶文本的book模塊:
通過:
from nltk.book import *
可導入nltk.book的所有模塊,並且該模塊自帶9本書可以作爲文本分析的例子,內容如下:
參考翻譯書名:《白鯨記》、《理智與情感》、《聖經》、《總統就職演說語料庫》、《聊天語料庫》、《巨蟒與聖盃》、《華爾街之旅》、《人事語料庫》以及《星期四人》
此外,對於每本書的第一句,該模塊都給出了一個特殊的變量供讀者使用。例如,《白鯨記》的第一句即爲變量sent1,《聖經》的第一句爲sent3等等。每句話所代表的變量是一個字符(token,包括單詞、符號和數字)組成的列表
文本基本信息數據統計:
len(text)函數:
對於nltk中的文本,使用len(text)函數可以統計出文本中字符的個數。
"""
Numbers of words, punctuations and numbers (tokens)
"""
len(text1)
nltk中,所有的文本以python 列表形式儲存,因此所有對於Python列表成立的操作對於nltk文本也適用。以下代碼分別獲取文本中獨立的單詞以及這些單詞中按照字母排列的前10個單詞:
# num of unique tokens
len(set(text1))
# Get part of the list
sorted(set(text3))[25 : 35]
因此,文本中平均每個單詞出現的次數(文本多樣程度, lexical diversity)可以計算如下:
diversity = len(text) / len(set(text))
count() 函數:
使用count()函數可以統計文本中出現的關鍵詞的次數:
text4.count('America')
並可以統計關鍵詞佔比:
# How would you calculate the percentage of Text 4 that is taken up by the word "America"?
print("Percentage of \"America\" %.3f %% " % ((text4.count('America') / len(text4)) * 100))
對於文本中出現的一些單詞,還可以畫出其分佈情況:
# 畫出文本4中以下單詞的分類情況
import numpy as np
%matplotlib inline
text4.dispersion_plot([ "citizens", "democracy", "freedom", "duties", "America"])
簡要文本搜索
concordance(key_word)函數:搜索關鍵詞在文本中出現的上下文:
以下代碼搜索關鍵詞"monstrous"在文本text1中出現的前後文:
text1.concordance('monstrous')
此外,還可以限制每行文本的長度以及所顯示的文本總數。例如,以下代碼搜索關鍵詞"the"出現的前後文,限制每行顯示79個字符,並只顯示前100個結果:
text1.concordance("the", 79, lines=100)
搜索功能還包括一個具體的關鍵詞在文本中第一次出現的下標(是文本中第幾個單詞,從0開始數):
print(text4.index('awaken'))
print(text4[0])
similar(key_word)函數:搜索關鍵詞在文本中的其他近義詞:
text2.similar('monstrous')
collocations()函數:搜索文本中的常見關鍵詞組:
該函數可以搜索出文本中經常出現的詞組。
text4.collocations()
文本詞頻統計相關模塊:
NLTK中常用FreqDist和Counter模塊做詞頻統計。
from nltk.probability import FreqDist
from collections import Counter
most_common(num):統計最常見的num個字符
以下代碼輸出被統計文本中最常見的50個字符:
fdist1 = FreqDist(text1)
fdist1.most_common(50)
可以看到,統計結果中有許多標點符號,可能在文本分析中並沒有實際意義。因此,作如下處理可以得到僅含有最常見的50個單詞的列表:
text1 = [word for word in text1 if word.isalpha()]
fdist1 = FreqDist(text1)
fdist1.most_common(50)
文本統計中將nltk模塊與常見python字符串處理函數進行混合也是一種常見文本處理手段。適合於nltk一起使用的常見python字符串處理手段如下表:
fDist[word]: 統計該單詞在文本中的出現次數:
文本統計可以統計某一個單詞在文本中出現的次數,比如:
fdist1['whale']
統計了whale這個單詞在《白鯨記》中出現的次數。
以下代碼分別繪製最常用50個字符的頻率以及他們總計的詞頻量:
fDist.plot(num, cumulative=False):繪製最常見的num個單詞的分佈情況
fdist1.plot(50)
fdist1.plot(50, cumulative=True)
fDist.max()和fDist.freq(num):文本中最常出現的單詞的長度和最常出現的單詞佔比
以下代碼統計了文本《白鯨記》中最常見的單詞的長度:
fdist2 = FreqDist(len(word) for word in text1)
# 3 letter words are most common
fdist2.max()
反過來,也可以統計三個字母組成的單詞所佔總字符數的比例:
# What is the freq of 3 letter words?
fdist2.freq(3)
其他常見的詞頻統計方式如圖所示:
以下代碼輸出文本中長於15個字母的單詞:
vocab = set(text4)
long_words = [word for word in vocab if len(word) > 15]
sorted(long_words)
Counter 模塊則常用語統計多元詞組(由多個單詞組成的詞組)相關信息。
import operator
from collections import Counter
threshold = 2
ng = 3
testtext = tokens
#Create out ngram, convert to a list,
#run a counter to count the number of entries for each unique list element
raw_grams = ngrams(testtext, ng)
listgrams = list(raw_grams)
counts = Counter(listgrams)
print(len(listgrams), len(counts))
#Create a regular dictionary, this is mostly done so we can ignore Counter values less than threshold
D = {}
for k,v in counts.items():
if v > threshold:
D[k] = v
#Here is a way to sort a dictionary, based on the value (key=operator.itemgetter(1))
sorted_x = sorted(D.items(), key=operator.itemgetter(1), reverse=True)
比如,上述代碼統計了tokens這個給定文本中重複兩次以上三元詞組及其頻率。
附:Jupyter notebook使用簡介:
本文代碼展示環境爲Jupyter notebook (舊名IPython notebook),這是一款瀏覽器交互型Python代碼編輯器。文本處理中最常見功能(快捷鍵)如下:
- A:在當前代碼格上方新建代碼格
- B:在當前代碼格下方新建代碼格
- D兩次:刪除該格
- Ctrl + Enter: 運行格中的Python代碼
- Shift + M:合併代碼格
- Shift + Tab: 在jupyter notebook中顯示python模塊的用處
- Tab: 自動補全代碼
- 此外,單擊 View -> Toggle line numbers,即可顯示行號。
- 關於Jupyter notebook路徑的選擇,Windows下可以cmd到某文件夾,然後運行jupyter notebook。
如果需要改變Jupyter的默認工作路徑(一般爲C盤用戶名下的文件),則需要打開cmd,輸入"jupyter notebook --generate-config"。然後打開“jupyter_notebook_config.py” 這個文件(通常路徑在“C:\Users\user_name.jupyter”)中,將下列代碼
#c.NotebookApp.notebook_dir = ' '
改爲:
c.NotebookApp.notebook_dir = 'absolute_path_you_need'
此處absolute_path_you_need即爲用戶指定的工作環境。
注意:在Windows下,需要右擊快捷方式,將“屬性->目標”這一欄改爲啓動的絕對路徑。
備註:如果需要更改啓動notebook的瀏覽器(如改成chrome),可以輸入:
import webbrowser
webbrowser.register('chrome', None, webbrowser.GenericBrowser(u'E:\chromeportable\chrome.exe'))
c.NotebookApp.browser = 'chrome'`
在Jupyter notebook中,通過直接鍵入模塊+問號的形式即可獲得文檔使用幫助。如:
numpy.average?
即可獲得關於numpy中average這個函數的說明。
參考資料:
- NLTK官方文檔,http://www.nltk.org/
- NLTKbook模塊官方文檔,http://www.nltk.org/book/
- 墨爾本大學科研委員會(Resbaz)NLTK培訓課程
- Jupyter notebook常見快捷鍵:https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcut
- 更改Jupyter notebook起始目錄的四種方法,URL:https://blog.csdn.net/qq_33039859/article/details/54604533