獲得文字語料和詞彙資源(一)
阿新 • • 發佈:2019-02-11
#python3
import nltk
nltk.corpus.gutenberg.fileids()#古騰堡專案
emma=nltk.corpus.gutenberg.words('austen-emma.txt')#《艾瑪》
另一種匯入方式:
from nltk.corpus import gutenberg
gutenberg.fileids()
emma=gutenberg.words('austen-emma.txt')
語料庫訪問方法之間區別:
raw('a.txt')能求出文字中語料庫的原始內容
sent()函式把文字劃分為句子,每一個句子是一個詞連結串列
raw=gutenberg.raw("burgess-busterbrown.txt" )
raw[1:20]
#'The Adventures of B'
words=gutenberg.words("burgess-busterbrown.txt")
words[1:20]
# ['The','Adventures', 'of','Buster','Bear','by','Thornton','W','.','Burgess','1920',']','I','BUSTER','BEAR','GOES','FISHING','Buster','Bear']
sents=gutenberg.sents("burgess-busterbrown.txt")
sents[1:20]
# [['I'], ['BUSTER', 'BEAR', 'GOES', 'FISHING'],
['Buster'...]]
#載入自己的語料庫(這樣的感覺很不錯)
from nltk.corpus import PlaintextCorpusReader
address=r"F:\good"#需要載入的檔案的具體目錄
wordlist=PlaintextCorpusReader(address,'.*')#這裡用到了正則表示式進行匹配
wordlist.fileids()
#['a.txt']
wordlist.words('a.txt')
#['sfajl', ',', 'sfsdlkfw', ',', 'wef', ',', 'wefwko', ...]
wordlist.raw('a.txt' )
#'sfajl,sfsdlkfw ,wef,wefwko,wefkl,' 原始內容
bigrams()函式接受一個詞彙連結串列,並建立起一個連續的詞對連結串列
cfdist=ConditionalFreqDist(pairs)#從配對連結串列中建立條件頻率分佈,就是說pairs應為經過bigrams()函式處理過的
cfdist[condition]#此條件下的頻率分佈
cfdist[condition][sample]#此條件下給定樣本的頻率分佈
cfdist.tabulate()#為條件概率繪製分佈製表
cfdist[word].max上下文中最有可能的識別符號
#過濾文字函式:計算文字的詞彙表,刪除所有與現有的詞彙表中出現的元素,只留下罕見或者拼寫錯誤的詞彙。
def unusual_words(text):
text_vocab=set(w.lower() for w in text if w.isalpha())
english_vocab=set(w.lower() for w in nltk.corpus.words.words())
unusual=text_vocab.difference(english_vocab)
return sorted(unusual)
停用詞語料庫,進一步進行處理之前需要將它們從文件中過濾
from nltk.corpus import stopwords
stopwords.words('english')
包括高頻詞彙:the,to,and等,使得區分文字變得簡單。
FreqDist()比較法可以檢測候選詞中每個單詞的頻率