NLTK學習筆記(二):文本、語料資源和WordNet匯總

來源:互聯網
上載者:User

標籤:正則   目錄      cti   函數   頻率   範圍   字典   詞彙   

[TOC]

語料庫基本函數表
樣本 描述
fileids() 語料庫中的檔案
fileids([categories]) 對應分類中的語料庫檔案
categories() 語料庫的分類
categories([fileids]) 檔案對應的語料庫分類
raw(fileids=[f1,f2..],categories=[c1,c2...]) 對應檔案和分類中原始內容。參數可以式空
words(fileids=[f1,f2..],categories=[c1,c2...]) 對應檔案和分類的詞彙。參數可以空
sents() sents(fileids=[f1,f2..],categories=[c1,c2...])
abspath(fileid) 檔案在磁碟的位置
encoding(fileid) 檔案的編碼
open(fileid) 開啟檔案流
root() 本地語料庫corpus的位置
readme() README檔案的內容
文本語料庫分類
  1. 最簡單的是孤立的文本集合
  2. 按照文本等標籤分類組成結構,如:布朗語料庫
  3. 分類不嚴格,會重疊的語料庫,如:路透社語料庫
  4. 隨時間/語言用法改變的語料庫 ,如:就職演說庫
常見語料庫及其用法

注意nltk.Text(string) 返回類似text1的Text對象

古藤堡語料庫

包含36000本電子書,可以在這裡下載

from nltk.corpus import gutenbergprint(gutenberg.fileids())emma= gutenberg.words(‘austen-emma.txt‘)print(gutenberg.raw(‘austen-emma.txt‘))emma = nltk.Text(emma)#print(emma[:10])
網路&&聊天體

網路text主要是非正式文學,論壇交流,劇本,評論等。聊天文本是根據聊天室劃分的(檔案名稱包括 日期、聊天室、貼文量),被劃分為15個大檔案。

#網路體:webtextfrom nltk.corpus import webtextfor fileid in webtext.fileids():    print(fileid,webtext.raw(fileid)[:50])
[out]firefox.txt Cookie Manager: "Don‘t allow sites that set removegrail.txt SCENE 1: [wind] [clop clop clop] KING ARTHUR: Whooverheard.txt White guy: So, do you have any plans for this evenpirates.txt PIRATES OF THE CARRIBEAN: DEAD MAN‘S CHEST, by Tedsingles.txt 25 SEXY MALE, seeks attrac older single lady, for wine.txt Lovely delicate, fragrant Rhone wine. Polished lea
#聊天體:nps_chatfrom nltk.corpus import nps_chatchatroom = nps_chat.posts(‘10-19-20s_706posts.xml‘)chatroom[123:125]
[out][[‘i‘,  ‘do‘,  "n‘t",  ‘want‘,  ‘hot‘,  ‘pics‘,  ‘of‘,  ‘a‘,  ‘female‘,  ‘,‘,  ‘I‘,  ‘can‘,  ‘look‘,  ‘in‘,  ‘a‘,  ‘mirror‘,  ‘.‘], [‘hi‘, ‘U64‘]]
布朗語料庫

百萬詞級語料庫,沒啥好說的。按照文本分類,如新聞、社論等。

from nltk.corpus import brownprint(brown.categories())print(brown.fileids())

因為這個語料庫是研究文本間系統性差異的資源,所以可以來比較一下不同文本中情態動詞的用法。

import nltkfrom nltk.corpus import brownnews = brown.words(categories=‘news‘)fdist = nltk.FreqDist([w.lower() for w in news])modals= [‘can‘,‘could‘,‘may‘,‘might‘,‘must‘,‘will‘]for m in modals:    print(m,‘:‘,fdist[m])
路透社語料庫

新聞文檔,分為“訓練”和“測試”兩組。便於及其進行訓練和測試。命名就是‘test/number‘和‘training/number‘

from nltk.corpus import reutersprint(reuters.fileids())print(reuters.categories())
就職演說語料庫

感覺這算是美國特色吧。因為命名採用‘year-name.txt‘的格式,我們可以提取出來時間維度,並且做個折線圖來統計特定詞彙的出現頻率(不同年代中)

from nltk.corpus import inauguralprint(list(f[:4]for f in inaugural.fileids()))#下面體現American和citizen隨時間推移使用方式cfd = nltk.ConditionalFreqDist(                              (target,fileid[:4])                              for fileid in inaugural.fileids()                              for w in inaugural.words(fileid)                              for target in [‘america‘,‘citizen‘]                               if w.lower().startswith(target))cfd.plot()

感受一下(附)

載入自訂語料庫

如果想操作自己的語料庫,並且使用之前的方法,那麼,需要PlaintextCorpusReader 函數來載入他們,這個函數參數有兩個,第一個是根目錄,第二個是子檔案(可以使用Regex進行匹配)

from nltk.corpus import PlaintextCorpusReaderroot = r‘C:\Users\Asura-Dong\Desktop\tem\dict‘wordlist = PlaintextCorpusReader(root,‘.*‘)#匹配所有檔案print(wordlist.fileids())print(wordlist.words(‘tem1.txt‘))
輸出結果:[‘README‘, ‘tem1.txt‘][‘hello‘, ‘world‘]
詞典資源

詞典:包括詞性和注釋資訊。

停用詞語料庫

stopwords即是,遺憾的是沒有中文停用詞

from nltk.corpus import stopwords#定義一個計算func計算不在停用詞列表中的比例的函數def content(text):    stopwords_eng = stopwords.words(‘english‘)    content = [w for w in text if w.lower() and w not in stopwords_eng]    return len(content)/len(text)print(content(nltk.corpus.reuters.words()))
名字詞典

就兩部分組成,男性和女性的英文名字。這裡我們研究一下最後一個名字最後一個字母和性別的關係

names = nltk.corpus.namesprint(names.fileids())male = names.words(‘male.txt‘)female = names.words(‘female.txt‘)cfd = nltk.ConditionalFreqDist((fileid,name[-1]) for fileid in names.fileids() for name in names.words(fileid))cfd.plot()

(附)

發音詞典

這個更神奇,竟然是為了發音合成準備的。以後通讀這本書後,也想想怎麼遷移到中文上。

引入 nltk.corpus.cmudict 後,我們可以得到它音素的長度,由此可以找到押韻的詞語

s = [‘N‘,‘IHO‘,‘K‘,‘S‘]entries = nltk.corpus.cmudict.entries()print(‘Example:‘,entries[0])word_list = [word for word,pron in entries if pron[-4:]==s]print(word_list)

在因素表中,我們會發現數字:1,2,0。分別代表著:主重音、次重音、無重音。
這裡我們可以定義一個function,找到具有特定重音模式的詞彙

def func(pron):    return [char for phone in pron for char in phone if char.isdigit()]word_list = [w for w,pron in entries if func(pron)==[‘0‘,‘1‘,‘0‘,‘2‘,‘0‘]]print(word_list)
WordNet面向語義的英語字典

最後必須說一下這個字典。WordNet是由Princeton 大學的心理學家,語言學家和電腦工程師聯合設計的一種基於認知語言學的英語詞典。它不是光把單詞以字母順序排列,而且按照單詞的意義組成一個“單詞的網路”。

引入和同義字

motorcar和automobile是同義字,可以藉助wordnet來研究。

from nltk.corpus import wordnet as wnwn.synsets(‘motorcar‘)

結果是:[Synset(‘car.n.01‘)]。說明motorcar 只有一個 可能的含義。car.n.01被稱為“同義 詞集 ”。我們可以通過wn.synset(‘car.n.01‘).lemma_names 來查看當前同義字集的其他詞 (car這個單詞就有很多個同義字集了) 。wn.synset(‘car.n.01‘).examples 和wn.synset(‘car.n.01‘).definition 可以分別查看定義和例子(但是Python3裡面不可以。)

而類似car.n.01.car這樣的處於下一級的稱之為詞條
對於詞條層級的obj,可以看下面的操作。

print(wn.synset(‘car.n.01‘).lemmas)wn.lemma(‘car.n.01.automobile‘).namewn.lemma(‘car.n.01.automobile‘).synset
上位詞、下位詞、反義詞

上位詞(hypernym),指概念上外延更廣的主題詞。 例如:”花”是”鮮花”的上位詞,”植物”是”花”的上位詞,”音樂”是”mp3”的上位詞。反過來就是下位詞了。

上位詞和下位詞通過hyponyms() 和 root_hypernyms() 來訪問。

motorcar = wn.synset(‘car.n.01‘).hyponyms()#下位詞car = wn.synset(‘car.n.01‘).root_hypernyms()

反義詞就通過antonyms() 來訪問

其他詞集關係

之前是從上->到下,或者反過來。更重要的是從整體->局部,或者反過來。如大樹和樹冠、樹榦的關係,這些是part_meronyms() 。而大樹集合就成了森林,member_holonyms() 。而樹的實質是心材和邊材組成,即substance_meronyms()

語義相似性

當兩個單詞有相同的上位詞(在詞樹中尋找),而若上位詞恰好屬於較低層,那麼它們會有一定密切聯絡。

right = wn.synset(‘right_whale.n.01‘)orca = wn.synset(‘orca.n.01‘)print(right.lowest_common_hypernyms(orca))

當然,類似於樹的結構中總是有神的,可以通過min_depth() 來查看一個synset的最小深度。基於這些,我們可以在0-1的範圍內返回相似性。對於上面的代碼,查看相似性:right.path_similarity(orca)

這些數字大小意義不大。但是當鯨魚和鯨魚、鯨魚和小說來比較時,數字是減小的。對比著看大小,還是有意義的。

NLTK學習筆記(二):文本、語料資源和WordNet匯總

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.