使用NLTK
import nltk #導(dǎo)入nltk
nltk.download() #下載語料庫(kù)
使用官方教程中的文本
from nltk.book import *
尋找特定詞在文本中的上下文
text1.concordance("monstrous") #在text1中monstrous的上下文
依據(jù)上下文笆凌,尋找相似的詞語
text1.similar("monstrous")
text2.similar("monstrous")
尋找多個(gè)詞語在文本中的共同上下文
text2.common_contexts(["monstrous", "very"])
畫出詞語在文本中的位置信息圖
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])
對(duì)text文本進(jìn)行計(jì)數(shù)
len(text3) #文本text3的長(zhǎng)度
sorted(set(text3)) #按順序返回文本text3的全部詞語
len(set(text3)) #text3的無重復(fù)詞語數(shù)量圣猎、
len(set(text3)) / len(text3) #text3的“詞匯量豐富程度”
text3.count("smote") #“smote”在text3中出現(xiàn)的次數(shù)
“text”本質(zhì)上是一個(gè)詞語的列表(list)
sent1 = ['Call', 'me', 'Ishmael', '.'] #定義一個(gè)sent1
['Monty', 'Python'] + ['and', 'the', 'Holy', 'Grail'] #連接兩個(gè)list
sent4 + sent1 #連接兩個(gè)list
sent1.append("Some") #為sent1添加詞語元素
text4[173] #返回'awaken'
text4.index('awaken') #返回索引值173
text5[16715:16735]
詞語本身就是python中的字符串(string)
name = 'Monty'
name[:4] #'Mont'
name * 2 #'MontyMonty'
name + '!' #'Monty!'
' '.join(['Monty', 'Python']) #'Monty Python'
'Monty Python'.split() #['Monty', 'Python']
對(duì)于文本信息的簡(jiǎn)單統(tǒng)計(jì)
使用頻率分布 frequency distribution
fdist1 = FreqDist(text1) #生成text1的頻率分布
fdist1.most_common(50) #輸出最常見的50個(gè)詞語及其出現(xiàn)次數(shù)
fdist1['whale'] #輸出特定詞語‘whale’的出現(xiàn)次數(shù)
簡(jiǎn)單的詞語篩選
V = set(text1)
long_words = [w for w in V if len(w) > 15] #篩選出長(zhǎng)詞
sorted(long_words)
fdist5 = FreqDist(text5)
sorted(w for w in set(text5) if len(w) > 7 and fdist5[w] > 7) #篩選出高頻長(zhǎng)詞
二元詞語搭配
list(bigrams(['more', 'is', 'said', 'than', 'done'])) #返回[('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')]乞而,全部的二元搭配
text4.collocations() #找到比我們根據(jù)單個(gè)詞的頻率預(yù)期更頻繁出現(xiàn)的二元詞