一肚豺、下載查看預(yù)料
使用python NLTK包,安裝什么的參考https://blog.csdn.net/huyoo/article/details/12188573
注:將nltk_data文件夾放在python運行環(huán)境的根目錄下界拦,方便調(diào)用語料吸申。
#下載要先調(diào)好語料的下載路徑。
import nltk
nltk.download('gutenberg') ##下載語料 要下載到nltk_data文件夾下
提問1:找出gutenberg的 shakespeare-macbeth.txt語料中最長的一句話。
from nltk.corpus import gutenberg
macbeth_sentences = gutenberg.sents('shakespeare-macbeth.txt')
#lenl = [len(s) for s in macbeth_sentences]
longest_len = max([len(s) for s in macbeth_sentences])
item = [s for s in macbeth_sentences if len(s) == longest_len]
提問2: 找出分析brown布朗語料庫中情態(tài)動詞
##nltk.download('brown') 下載
brown.categories() ##布朗語料庫種類
news_text = brown.words(categories = 'news') ##選擇新聞類
fdist = nltk.FreqDist([w.lower() for w in news_text]) ##詞頻統(tǒng)計
modals = ['can', 'could', 'may', 'might', 'must','will'] ##情態(tài)動詞
for m in modals:
print (m + ':', fdist[m],)
停用詞的應(yīng)用
定義一個函數(shù)截碴,計算文本中沒有在停用詞列表中的詞的比例
from nltk.corpus import stopwords
a = stopwords.words('english') #查看下english停用詞庫
def concont(text):
stopwords = nltk.corpus.stopwords.word('english')
content = [w for w in text if w.lower() not in stopwords]
return len(content) / len(text)
分析下names預(yù)料中尾字母和男女性別的關(guān)系
names = nltk.corpus.names
names.fileids() ##兩個男女姓名文件
male_names = names.words('male.txt')
female_names = names.words('female.txt')
##尾字母在各自文件夾中出現(xiàn)的次數(shù)
cfd = nltk.ConditionalFreqDist( (fileid, name[-1])
for fileid in names.fileids()
for name in names.words(fileid)
)
cfd.plot()
正則表達(dá)式
這里使用words語料梳侨,下載語料同上
匹配查找以ed結(jié)尾的詞匯
##
import re
wordlist = [w for w in nltk.corpus.words.words('en') if w.islower()]
resea_edend = [w for w in wordlist if re.search('ed$', w)]
匹配任何單個字符有一個8個字母組成的詞, j是其第三個字母,t是其第六個字母日丹。
rr = [w for w in wordlist if re.search('^..j..t..$', w)] ##“.”表示通配符
#^開頭走哺,$結(jié)尾,8個字母哲虾。
匹配數(shù)字
##+ 表示可以匹配多次 0.0085 0.05
te = [w for w in wsj if re.search('^[0-9]+\.[0-9]+$', w)]
##匹配出帶有字母和$的組合
zu = [w for w in wsj if re.search('^[A-Z]+\$$', w)]
##匹配出‘?dāng)?shù)字-字母(3到5次)’樣式 10-day
sz3 = [w for w in wsj if re.search('^[0-9]+-[a-z]{3,5}$', w)]
##匹配出以ed或者ing結(jié)尾的單詞
edin = [w for w in wsj if re.search('(ed|ing)$', w)]
最后 re.split丙躏,join 常用方法格式如下
re.split(r'\W+', str) 以所有字母,數(shù)字束凑,下劃線以外的字符進(jìn)行拆分晒旅。
silly = ['We', 'called', 'him', 'Tortoise']
' '.join(silly) ##we called him Tortoise