1.簡介
NLTK (Natural Language Toolkit) 是自然語言處理(NLP)任務的 Python 庫,內置大量NLP數據集與計算包。
NLP數據集也叫語料庫 (Corpus), 若無特殊格式或標記,數據集通常來自txt等文本文件。
本教程內容適用版本:
- nltk = 3.8.1
- python = 3.7.2
1.1 主要模塊
涵蓋NLP基本操作和大量語料(英文為主):
Module | 功能描述 (EN / 中文) | 典型用途 / 算法術語 |
---|---|---|
nltk.corpus | Text corpora and lexical resources / 文本語料庫和詞匯資源 | Brown、Gutenberg 等語料庫;WordNet 詞典、停用詞表等 |
nltk.tokenize / nltk.stem | Text tokenization and stemming (split text into words/sentences; remove affixes) / 文本分詞和詞干提取(拆分為單詞/句子;移除詞綴) | 單詞/句子分詞(word_tokenize 、sent_tokenize );Porter、Lancaster、Snowball 詞干算法 |
nltk.collocations | Identify collocations (frequently co-occurring word combos) / 搭配詞發現(識別高頻共現詞組) | 雙字/三字搭配;關聯度量 (PMI, χ2, t-檢驗, 似然比) |
nltk.tag | Part-of-speech tagging (assign POS tags) / 詞性標注(為單詞分配詞性標簽) | HMM、CRF、最大熵等詞性標注器 |
nltk.classify / nltk.cluster | Classification & clustering / 分類與聚類 | 文本分類(樸素貝葉斯、最大熵、SVM);聚類(K-means、EM) |
nltk.chunk | Chunking (shallow parsing, phrase extraction) / 短語切分(淺層解析,如名詞短語提取) | 正則表達式分塊;IOB 標記;基礎名詞/動詞短語 |
nltk.parse | Parsing (syntactic analysis) / 句法分析(生成句子結構樹) | CFG/PCFG 解析;移進-歸約、CKY、圖譜解析(Chart) |
nltk.sem / nltk.inference | Semantic interpretation & inference (represent meaning in logic) / 語義表示與邏輯推理 | 一階邏輯 (FOL,表示含義);定理證明 (Prover9) 、模型構建 (Mace) |
nltk.metrics | Evaluation metrics / NLP評估指標 | Precision、Recall、F1、Accuracy(精確率、召回率、F1 值、BLEU、混淆矩陣分析等) |
nltk.probability | Probability distributions / 概率分布(頻率分布與條件概率分布) | FreqDist、ConditionalFreqDist;最大似然估計 (MLE)、拉普拉斯平滑 |
nltk.lm | Language modeling / 語言模型 | n-gram 模型(unigram/bigram, 基于統計);Kneser-Ney/Laplace 平滑;Perplexity (困惑度) |
nltk.app / nltk.chat | Interactive demos & chatbots / 交互式示例程序和聊天機器人 | GUI 演示(Chart Parser、WordNet 瀏覽器);Eliza/Zen 聊天機器人 |
nltk.toolbox | Toolbox format I/O / 田野語言學工具(處理 SIL Toolbox 格式) | 標準格式標記 (SFM) 解析器 |
1.2 Corpus內置方法
這里以小說nltk.corpus.gutenberg的圣經(‘bible-kjv.txt’)為例:
類別 | 方法 / 屬性 | 示例代碼 | 說明 |
---|---|---|---|
讀取文本結構 | fileids() | gutenberg.fileids() | 獲取所有文本文件名 |
raw(fileid) | gutenberg.raw('bible-kjv.txt') | 原始文本字符串 | |
words(fileid) | gutenberg.words('bible-kjv.txt') | 單詞列表(空格+標點分割) | |
sents(fileid) | gutenberg.sents('bible-kjv.txt') | 二維句子列表 | |
paras(fileid) | x.paras() (部分語料支持) | 三維段落列表 | |
文本分析 | FreqDist() | FreqDist(gutenberg.words(...)) | 詞頻分布 |
Text() | Text(gutenberg.words(...)) | 構建 NLTK Text 對象 | |
.concordance(word) | Text(...).concordance("God") | 查找關鍵詞上下文 | |
.similar(word) | Text(...).similar("God") | 查看上下文替換詞(語義近) | |
.common_contexts(["word1",...]) | Text(...).common_contexts(["God", "Lord"]) | 查看共現上下文 | |
.collocations() | Text(...).collocations() | 常見詞組搭配(PMI) | |
分詞/句分割 | word_tokenize() | word_tokenize(gutenberg.raw(...)) | 精細化分詞,保留標點 |
sent_tokenize() | sent_tokenize(gutenberg.raw(...)) | 精細化句子切分 | |
nltk.ngrams() | list(ngrams(tokens, 3)) | n-gram 構造 | |
詞性標注 | pos_tag() | pos_tag(tokens[:50]) | 給詞打詞性標簽 |
詞性標注表 | nltk.help.upenn_tagset('VB') | help.upenn_tagset('NN') | 查看 Penn Treebank 詞性定義 |
其他常用 | Text(...).generate() | Text(...).generate() | 基于詞序列生成文本(n-gram) |
2. 語料庫簡介(Overview)
nltk.corpus 模塊中包含了多種類型的語料庫,可大致分為以下幾類:
2.1. 文本語料庫(Text Corpora)
用于自然語言處理中的分詞、句法、語義、風格等分析。
常見示例:
- gutenberg:18 本經典英文文學作品
- brown:1961 年的美國英語通用語料庫(500 文本)
- reuters:路透社新聞分類語料(10,000+ 文本)
- inaugural:歷屆美國總統就職演講
- webtext:網絡體文本(Reddit、電影評論等)
2.2 詞匯資源(Lexical Resources)
用于詞性、語義關系、拼寫、發音等詞匯分析。
常見示例:
- wordnet:英文詞義庫(支持同義詞、反義詞、上下義等)
- cmudict:CMU 發音詞典
- words:英語常見單詞列表
- names:常見英文人名
- stopwords:英文停用詞列表
2.3. 分類語料(Categorized Corpora)
帶標簽的數據,常用于分類、監督學習等任務。
常見示例:
- movie_reviews:IMDb 影評,正/負情感標簽
- reuters:每篇文章帶多個主題標簽
- subjectivity:主觀/客觀句子分類
- product_reviews_1:商品評論(分類任務)
2.4 標注語料(Tagged Corpora)
帶詞性標注的語料,適用于詞性標注訓練/測試。
常見示例:
- treebank:賓州樹庫(句法分析)
- brown(也有 POS 標簽版本)
- conll2000:用于語塊(chunking)任務
2.5 多語言語料(Multilingual Corpora)
支持多種語言的語料庫。
常見示例:
- udhr:世界人權宣言的多語言版本(Universal Declaration of Human Rights)
- cess_cat / cess_esp:加泰羅尼亞語 / 西班牙語語料
2.6 聊天語料與對話(Chat Corpora)
- nps_chat:在線聊天對話句子,帶標簽
2.7. 句法結構樹(Parsed Corpora)
- treebank:提供帶結構樹的語法分析句子
- dependency_treebank:依存句法分析樹
3.文本語料庫(Text Corpora)
3.1 古騰堡項目 Gutenberg
NLTK 的 gutenberg 語料庫來自 Project Gutenberg 項目,包含公開版權的經典文學作品(小說)。內容包含全部正文(不刪節)、 版權提示或書籍元信息(可手動清洗)。文本通常來源 .txt,沒有章節分隔符、元數據標簽等結構化信息。有時附帶序言、腳注等,比如莎士比亞文本中會包含劇本角色說明等附加內容。
- 輸出gutenberg小說總數(即文件名):
import nltk
print(nltk.corpus.gutenberg.fileids())
當前版本包含 18 本文學作品,如《愛瑪》《雙城記》《圣經》:
[‘austen-emma.txt’, ‘austen-persuasion.txt’, ‘austen-sense.txt’, ‘bible-kjv.txt’, ‘blake-poems.txt’, ‘bryant-stories.txt’, ‘burgess-busterbrown.txt’, ‘carroll-alice.txt’, ‘chesterton-ball.txt’, ‘chesterton-brown.txt’, ‘chesterton-thursday.txt’, ‘edgeworth-parents.txt’, ‘melville-moby_dick.txt’, ‘milton-paradise.txt’, ‘shakespeare-caesar.txt’, ‘shakespeare-hamlet.txt’, ‘shakespeare-macbeth.txt’, ‘whitman-leaves.txt’]
具體信息如下:
ID | 文件名 | 作品名稱(英文) | 作者(英文) | 中文簡介 |
---|---|---|---|---|
1 | austen-emma.txt | Emma | Jane Austen | 簡·奧斯汀《愛瑪》 |
2 | austen-persuasion.txt | Persuasion | Jane Austen | 簡·奧斯汀《勸導》 |
3 | austen-sense.txt | Sense and Sensibility | Jane Austen | 簡·奧斯汀《理智與情感》 |
4 | bible-kjv.txt | Bible (King James Version) | 多人編纂 | 《圣經》欽定版(英王詹姆斯版) |
5 | blake-poems.txt | Poems (1789) | William Blake | 威廉·布萊克詩集(如《天真與經驗之歌》) |
6 | bryant-stories.txt | Stories to Tell to Children | Sara Cone Bryant | 兒童故事集(薩拉·C·布萊恩特) |
7 | burgess-busterbrown.txt | Buster Brown | Thornton W. Burgess | 兒童故事《巴斯特·布朗》 |
8 | carroll-alice.txt | Alice’s Adventures in Wonderland | Lewis Carroll | 劉易斯·卡羅爾《愛麗絲夢游仙境》 |
9 | chesterton-ball.txt | The Ball and the Cross | G. K. Chesterton | 《球與十字架》 |
10 | chesterton-brown.txt | The Innocence of Father Brown | G. K. Chesterton | 《布朗神父探案集》 |
11 | chesterton-thursday.txt | The Man Who Was Thursday | G. K. Chesterton | 《星期四出生的男人》 |
12 | edgeworth-parents.txt | The Parent’s Assistant | Maria Edgeworth | 《父母助手》(教育寓言故事集) |
13 | melville-moby_dick.txt | Moby-Dick; or, The Whale | Herman Melville | 赫爾曼·梅爾維爾《白鯨》 |
14 | milton-paradise.txt | Paradise Lost | John Milton | 彌爾頓《失樂園》 |
15 | shakespeare-caesar.txt | Julius Caesar | William Shakespeare | 莎士比亞《尤利烏斯·凱撒》 |
16 | shakespeare-hamlet.txt | Hamlet | William Shakespeare | 莎士比亞《哈姆雷特》 |
17 | shakespeare-macbeth.txt | Macbeth | William Shakespeare | 莎士比亞《麥克白》 |
18 | whitman-leaves.txt | Leaves of Grass | Walt Whitman | 惠特曼《草葉集》 |
3.1 Bible (King James Version)-ID4
- 數據信息:
- 總詞數:約 1,010,654。
- 總句數:約 30,103。
- 詞匯量:約 13,769 個唯一單詞。
- 最常見tokens:(‘,’, 70509), (‘the’, 62103), (‘:’, 43766), (‘and’, 38847)。
- 平均句長:約 33.57 個單詞。
- 常見搭配:(‘,’, ‘and’), (‘the’, ‘LORD’), (“'”, ‘s’), (‘of’, ‘the’) 等。
- 包含 “God” 的句子:約 3,423 句。
以下是上述信息的部分輸出(bible-kjv.txt):
from nltk.corpus import gutenberg, stopwords
from nltk.tokenize import word_tokenize
import string# 獲取原始文本
bible_text = gutenberg.raw('bible-kjv.txt')
print(bible_text[:100]) # 打印前 100 個字符, 輸出示例: "[The King James Bible]\n\nThe Old Testament of ..."
print('----------')# 獲取單詞列表
bible_words = gutenberg.words('bible-kjv.txt')
print(bible_words[:10]) # 打印前 10 個單詞, 輸出示例: ['[', 'The', 'King', 'James', 'Bible', ']', 'The', 'Old', 'Testament', 'of']
print(len(bible_words)) # 統計總詞數, 輸出示例: 約 1,010,654 個單詞
print('----------')# # 獲取句子列表
bible_sents = gutenberg.sents('bible-kjv.txt')
print(bible_sents[:2]) # 打印前 2 個句子: [['[', 'The', 'King', 'James', 'Bible', ']'], ['The', 'Old', 'Testament', 'of', 'the', 'Holy', 'Bible']]
print(len(bible_sents)) # 統計總句數, 輸出示例: 約 30,103 個句子
print('----------')# # 詞匯量(去重后的單詞數)
vocab = set(bible_words)
print(f"詞匯量: {len(vocab)}") # 輸出示例: 約 13, 769 個唯一單詞(詞匯量)
print('----------')# # 平均句長(單詞數)
avg_sent_len = sum(len(sent) for sent in bible_sents) / len(bible_sents)
print(f"平均句長: {avg_sent_len:.2f} 個單詞") # 輸出示例: 約 33.57 個單詞
print('----------')# # 詞頻統計
from nltk import FreqDist
freq_dist = FreqDist(bible_words)
print(freq_dist.most_common(10))
# 打印最常見的 10 個單詞: [(',', 70509), ('the', 62103), (':', 43766),
# ('and', 38847), ('of', 34480), ('.', 26160), ('to', 13396), ('And', 12846), ('that', 12576), ('in', 12331)]
print('----------')# 分詞
raw_text = bible_text[:500] # 取前 500 字符示例
tokens = word_tokenize(raw_text) # 格式區別sents()方法,其按列表元素分割句子, 句子內為粉刺
print(tokens[:10]) # 輸出示例: ['[', 'The', 'King', 'James', 'Bible', ']', 'The', 'Old', 'Testament', 'of']
print('----------')# 移除標點和停用詞
stop_words = set(stopwords.words('english') + list(string.punctuation))
cleaned_tokens = [w.lower() for w in tokens if w.lower() not in stop_words]
print(cleaned_tokens[:10]) # 輸出示例: ['king', 'james', 'bible', 'old', 'testament', 'king', 'james', 'bible', 'first', 'book']
# with open('cleaned_bible_words.txt', 'w') as f:
# f.write('\n'.join(cleaned_tokens)) # 保存清洗后的單詞到文件
print('----------')# 對前 100 個單詞進行詞性標注
from nltk import pos_tag
words = bible_words[:100]
tagged_words = pos_tag(words)
print(tagged_words[:10]) # 打印前 10 個詞的詞性
# [('[', 'VB'), ('The', 'DT'), ('King', 'NNP'), ('James', 'NNP'),
#('Bible', 'NNP'), (']', 'VBZ'), ('The', 'DT'), ('Old', 'NNP'), ('Testament', 'NNP'), ('of', 'IN')]
print('----------')# 查找包含 "God" 的句子
god_sents = [sent for sent in bible_sents if 'God' in sent]
print(f"包含 'God' 的句子數: {len(god_sents)}") # 輸出示例: 約 3,423 句
print(god_sents[0]) # 打印第一個匹配的句子
# 輸出示例: ['1', ':', '1', 'In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
print('----------')# 查找常見雙詞搭配
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
finder = BigramCollocationFinder.from_words(bible_words)
finder.apply_freq_filter(10) # 過濾出現次數少于 10 的搭配
collocations = finder.nbest(BigramAssocMeasures.likelihood_ratio, 10)
print(collocations)
# [(',', 'and'), ('the', 'LORD'), ("'", 's'), ('of', 'the'),
#('shall', 'be'), ('I', 'will'), ('in', 'the'), ('said', 'unto'), (';', 'and'), ('thou', 'shalt')]
print('----------')
3.2 The Parent’s Assistant-ID12
-
數據信息(總量約圣經的1/3-1/4):
- 總詞數:約 210,663。
- 總句數:約 10,230。
- 詞匯量:約 9,593 個唯一單詞。
- 最常見tokens:(‘,’, 15219), (‘the’, 7149), (‘.’, 6945), (‘to’, 5150)。
- 平均句長:約 20.60 個單詞。
- 常見搭配:(“'”, ‘s’), (‘,"’, ‘said’), (‘,’, ‘and’), (‘."’, ‘"’) 等。
- 包含 “God” 的句子:約 17 句。
-
小說信息:
《The Parent’s Assistant;》是瑪麗亞·埃奇沃斯(Maria Edgeworth)創作的兒童故事集,首次出版于1796年,由約瑟夫·約翰遜(Joseph Johnson)發行。這部作品是兒童文學史上的重要里程碑,反映了啟蒙時代關于兒童教育和道德培養的觀念。瑪麗亞·埃奇沃斯(1768-1849)是一位英裔愛爾蘭作家、教育家和小說家,以其對兒童文學和現實主義小說的貢獻而聞名。
作者出生于英格蘭牛津郡,后隨家人移居愛爾蘭朗福德郡,協助父親管理家族莊園。她深受啟蒙運動和盧梭教育理念的影響,強調通過故事培養兒童的道德感和理性思維。《The Parent’s Assistant》是她最早的兒童文學作品之一,旨在為父母和教育者提供寓教于樂的素材。
作品不僅面向兒童,也通過道德故事引導父母反思教育方式。創作這部作品時,正值18世紀末的動蕩時期(如法國大革命、愛爾蘭叛亂),但埃奇沃斯選擇通過“安靜的鄉村生活場景”傳遞道德信息,展現她對社會穩定的關注。
該作品是一部短篇故事集,每個故事獨立成篇,聚焦兒童的日常生活、道德困境和成長經歷。故事通過引人入勝的敘事傳遞道德教訓,強調美德、勤奮、誠實和責任感等價值觀,以下是各篇故事的簡要介紹:
故事標題 | 中文譯名 | 主題與寓意 |
---|---|---|
Lazy Lawrence | 懶惰的勞倫斯 | 批評懶惰,強調勤奮和自律的重要性。 |
Tarlton | 塔爾頓 | 揭示輕信和不良同伴的危險,鼓勵兒童選擇正直的朋友。 |
The False Key | 假鑰匙 | 故事教導誠實是最佳選擇,欺騙終將暴露。 |
The Orange Man | 賣橙人 | 講述誠實與貪婪的對比,強調誠實、同情心和公平對待他人的重要性。 |
The Little Dog Trusty | 小狗特魯斯蒂 | 通過小狗的忠誠和兒童的冒險,教導兒童信守承諾并珍惜可靠的伙伴。 |
The Barring Out, or Party Spirit | 罷課,或黨派精神 | 批評盲目從眾,強調獨立思考與責任感。 |
The Birthday Present | 生日禮物 | 批判盲目追隨時尚與虛榮的傾向,強調實用與節制。 |
Simple Susan | 單純的蘇珊 | 贊揚純真與善良,強調同情心與家庭責任。 |
The Bracelets | 手鐲 | 探討虛榮與真實價值,強調內在美的重要性。 |
The Little Merchants | 小商人 | 通過兒童經營小生意的經歷,強調公平交易和誠實經商的重要性。 |
The Purple Jar | 紫色罐子 | 探討選擇與后果,強調為自己的行為負責。 |
Old Poz | 老波茲 | 講述假裝公正卻自私的偽善危害,以幽默方式傳達正義與公平理念。 |
The Mimic | 模仿者 | 通過模仿他人缺點的故事警示盲目模仿的危險,教導保持自我并尊重他人 |
Mademoiselle Panache | 潘娜小姐 | 批評虛榮與表面功夫,強調真實與誠實。 |
The Basket Woman | 籃子女人 | 講述賣籃女通過勤勞和智慧改善生活,鼓勵尊重勞動者并學會自立。 |
The White Pigeon | 白鴿 | 講述善良與回報的故事,強調善行的重要性。 |
The Orphans | 孤兒 | 探討社會責任,鼓勵上層階級以知識和善行幫助弱勢群體。 |
Waste Not, Want Not | 勤儉節約 | 通過兩個男孩對待食物的不同態度,教導避免浪費和規劃未來的重要性。 |
Forgive and Forget | 寬恕與遺忘 | 通過兒童間的爭吵與和解,強調寬容與原諒,促進和諧人際關系。 |
Eton Montem | 伊頓蒙特姆 | 通過伊頓公學, 探討集體活動的責任與紀律,鼓勵在群體中保持品格和理性。 |
-
部分故事簡介:
-
《The Orphans》:故事以愛爾蘭羅斯莫爾城堡廢墟附近的一位寡婦和她的四個孩子為背景。寡婦病重,臨終前囑咐長女瑪麗照顧弟妹。母親去世后,孤兒們面臨經濟困境和驅逐危機。瑪麗通過紡紗和勞作還清債務,帶領弟妹在城堡廢墟中找到庇護。社區的善意支持他們生存,展現了家庭忠誠和自力更生的主題。
-
《The Purple Jar》:講述女孩羅莎蒙德在商店看到一個紫色罐子,執意要買,但母親讓她在罐子和實用鞋子間選擇。她選擇了罐子,卻發現它只是普通玻璃罐,毫無價值。這個故事教導兒童權衡選擇和延遲滿足的重要性。
-
-
截取完整的一部小說
我們從該語料庫中截取一部完整的小說《THE WHITE PIGEON》:
import nltk
from nltk.corpus import gutenberg# 確保已下載所需的 NLTK 數據
nltk.download('gutenberg')# 加載文本
text = gutenberg.raw('edgeworth-parents.txt')# 定義故事的起始和結束標志
start_marker = 'THE WHITE PIGEON'
end_marker = 'THE BIRTHDAY PRESENT'# 查找起始和結束位置
start_index = text.find(start_marker)
end_index = text.find(end_marker)# 確保找到標志
if start_index != -1 and end_index != -1:# 提取故事內容story_text = text[start_index:end_index].strip() # 移除這些首尾字符 1.空格 ' ',2.制表符 \t,3.換行符 \n,4.回車符 \r# 保存到本地文件with open('the_white_pigeon.txt', 'w', encoding='utf-8') as f:f.write(story_text)print("《The White Pigeon》已成功保存到 'the_white_pigeon.txt' 文件中。")
else:print("未能找到指定的故事段落,請檢查標志是否正確。")
該故事token數量:3,936,唯一token數量:930
3.3 Reuters
- 路透社新聞語料庫,當前版本有 10,788 篇新聞文章;
- 每個新聞包含多個標簽(>=1),通過api提供,適合文本分類任務;
唯一不足,沒有新聞日期
- 數據文件格式:
[‘test/14826’, ‘test/14828’, ‘test/14829’,…, ‘training/9994’, ‘training/9995’]
- 數據信息
- 新聞數量 (Total documents): 10,788
- 總詞數 (Total tokens): 1,720,901
- 總句數 (Sentences): 54,716
- 詞匯量: 41,600
- 平均句長: 31.45 個單詞
- 最常見tokens:(‘.’, 94687), (‘,’, 72360), (‘the’, 58251), (‘of’, 35979)。
- 常見搭配:(‘&’, ‘lt’), (‘lt’, ‘;’), (“'”, ‘s’), (‘,’, ‘000’)等。
- 包含 “God” 的句子:1 句。
完整標簽包括:
[‘acq’, ‘alum’, ‘barley’, ‘bop’, ‘carcass’, ‘castor-oil’, ‘cocoa’, ‘coconut’, ‘coconut-oil’, ‘coffee’, ‘copper’, ‘copra-cake’, ‘corn’, ‘cotton’, ‘cotton-oil’, ‘cpi’, ‘cpu’, ‘crude’, ‘dfl’, ‘dlr’, ‘dmk’, ‘earn’, ‘fuel’, ‘gas’, ‘gnp’, ‘gold’, ‘grain’, ‘groundnut’, ‘groundnut-oil’, ‘heat’, ‘hog’, ‘housing’, ‘income’, ‘instal-debt’, ‘interest’, ‘ipi’, ‘iron-steel’, ‘jet’, ‘jobs’, ‘l-cattle’, ‘lead’, ‘lei’, ‘lin-oil’, ‘livestock’, ‘lumber’, ‘meal-feed’, ‘money-fx’, ‘money-supply’, ‘naphtha’, ‘nat-gas’, ‘nickel’, ‘nkr’, ‘nzdlr’, ‘oat’, ‘oilseed’, ‘orange’, ‘palladium’, ‘palm-oil’, ‘palmkernel’, ‘pet-chem’, ‘platinum’, ‘potato’, ‘propane’, ‘rand’, ‘rape-oil’, ‘rapeseed’, ‘reserves’, ‘retail’, ‘rice’, ‘rubber’, ‘rye’, ‘ship’, ‘silver’, ‘sorghum’, ‘soy-meal’, ‘soy-oil’, ‘soybean’, ‘strategic-metal’, ‘sugar’, ‘sun-meal’, ‘sun-oil’, ‘sunseed’, ‘tea’, ‘tin’, ‘trade’, ‘veg-oil’, ‘wheat’, ‘wpi’, ‘yen’, ‘zinc’]
3.4 布朗語料庫 Brown
1961 年的布朗語料庫,是經典的均衡英語語料;按體裁分類(新聞、小說、宗教、科技等),共 500 文本,總詞數約百萬級,句子偏短。
-
數據信息
- 新聞數量 (Total documents): 500
- 總詞數 (Total tokens): 1,161,192
- 總句數 (Sentences): 57,340
- 詞匯量: 56,057
- 平均句長: 20.25 個單詞
- 最常見tokens:(‘the’, 62713), (‘,’, 58334), (‘.’, 49346), (‘of’, 36080)。
- 常見搭配:無。
- 包含 “God” 的句子:278 句。
-
文件名前綴(分類)
原始數據的categories為簡寫(15類):
[‘adventure’, ‘belles_lettres’, ‘editorial’, ‘fiction’, ‘government’, ‘hobbies’, ‘humor’, ‘learned’, ‘lore’, ‘mystery’, ‘news’, ‘religion’, ‘reviews’, ‘romance’, ‘science_fiction’]
對應文件名與標簽對應,也為15類, 對于關系如下::
前綴 | 類別名稱(Category) | 描述 | 類別簡寫(categories) |
---|---|---|---|
ca | Press: reportage | 報刊報道 | news |
cb | Press: editorial | 報刊社論 | editorial |
cc | Press: reviews | 報刊評論 | reviews |
cd | Religion | 宗教文本 | religion |
ce | Skills and hobbies | 技能與愛好 | hobbies |
cf | Popular lore | 民間傳說、常識性話題 | lore |
cg | Belles lettres, biography, essays | 散文、美文、傳記等 | belles_lettres |
ch | Miscellaneous | 雜項(政府、報告、傳單等) | government |
cj | Learned (academic prose) | 學術文章 | learned |
ck | Fiction: general | 一般小說 | fiction |
cl | Fiction: mystery | 推理小說 | |
cm | Fiction: science fiction | 科幻小說 | |
cn | Fiction: adventure | 冒險小說 | |
cp | Fiction: romance | 言情小說 | |
cr | Fiction: humor | 幽默小說 |
- 文件名
這里ca有44個,cb24個, cr9個…, 500個文件名如下:
[‘ca01’, ‘ca02’, ‘ca03’, ‘ca04’, ‘ca05’, ‘ca06’, ‘ca07’, ‘ca08’, ‘ca09’, ‘ca10’, ‘ca11’, ‘ca12’, ‘ca13’, ‘ca14’, ‘ca15’, ‘ca16’, ‘ca17’, ‘ca18’, ‘ca19’, ‘ca20’, ‘ca21’, ‘ca22’, ‘ca23’, ‘ca24’, ‘ca25’, ‘ca26’, ‘ca27’, ‘ca28’, ‘ca29’, ‘ca30’, ‘ca31’, ‘ca32’, ‘ca33’, ‘ca34’, ‘ca35’, ‘ca36’, ‘ca37’, ‘ca38’, ‘ca39’, ‘ca40’, ‘ca41’, ‘ca42’, ‘ca43’, ‘ca44’, ‘cb01’, ‘cb02’, ‘cb03’, ‘cb04’, ‘cb05’, ‘cb06’, ‘cb07’, ‘cb08’, ‘cb09’, ‘cb10’, ‘cb11’, ‘cb12’, ‘cb13’, ‘cb14’, ‘cb15’, ‘cb16’, ‘cb17’, ‘cb18’, ‘cb19’, ‘cb20’, ‘cb21’, ‘cb22’, ‘cb23’, ‘cb24’, ‘cb25’, ‘cb26’, ‘cb27’, ‘cc01’, ‘cc02’, ‘cc03’, ‘cc04’, ‘cc05’, ‘cc06’, ‘cc07’, ‘cc08’, ‘cc09’, ‘cc10’, ‘cc11’, ‘cc12’, ‘cc13’, ‘cc14’, ‘cc15’, ‘cc16’, ‘cc17’, ‘cd01’, ‘cd02’, ‘cd03’, ‘cd04’, ‘cd05’, ‘cd06’, ‘cd07’, ‘cd08’, ‘cd09’, ‘cd10’, ‘cd11’, ‘cd12’, ‘cd13’, ‘cd14’, ‘cd15’, ‘cd16’, ‘cd17’, ‘ce01’, ‘ce02’, ‘ce03’, ‘ce04’, ‘ce05’, ‘ce06’, ‘ce07’, ‘ce08’, ‘ce09’, ‘ce10’, ‘ce11’, ‘ce12’, ‘ce13’, ‘ce14’, ‘ce15’, ‘ce16’, ‘ce17’, ‘ce18’, ‘ce19’, ‘ce20’, ‘ce21’, ‘ce22’, ‘ce23’, ‘ce24’, ‘ce25’, ‘ce26’, ‘ce27’, ‘ce28’, ‘ce29’, ‘ce30’, ‘ce31’, ‘ce32’, ‘ce33’, ‘ce34’, ‘ce35’, ‘ce36’, ‘cf01’, ‘cf02’, ‘cf03’, ‘cf04’, ‘cf05’, ‘cf06’, ‘cf07’, ‘cf08’, ‘cf09’, ‘cf10’, ‘cf11’, ‘cf12’, ‘cf13’, ‘cf14’, ‘cf15’, ‘cf16’, ‘cf17’, ‘cf18’, ‘cf19’, ‘cf20’, ‘cf21’, ‘cf22’, ‘cf23’, ‘cf24’, ‘cf25’, ‘cf26’, ‘cf27’, ‘cf28’, ‘cf29’, ‘cf30’, ‘cf31’, ‘cf32’, ‘cf33’, ‘cf34’, ‘cf35’, ‘cf36’, ‘cf37’, ‘cf38’, ‘cf39’, ‘cf40’, ‘cf41’, ‘cf42’, ‘cf43’, ‘cf44’, ‘cf45’, ‘cf46’, ‘cf47’, ‘cf48’, ‘cg01’, ‘cg02’, ‘cg03’, ‘cg04’, ‘cg05’, ‘cg06’, ‘cg07’, ‘cg08’, ‘cg09’, ‘cg10’, ‘cg11’, ‘cg12’, ‘cg13’, ‘cg14’, ‘cg15’, ‘cg16’, ‘cg17’, ‘cg18’, ‘cg19’, ‘cg20’, ‘cg21’, ‘cg22’, ‘cg23’, ‘cg24’, ‘cg25’, ‘cg26’, ‘cg27’, ‘cg28’, ‘cg29’, ‘cg30’, ‘cg31’, ‘cg32’, ‘cg33’, ‘cg34’, ‘cg35’, ‘cg36’, ‘cg37’, ‘cg38’, ‘cg39’, ‘cg40’, ‘cg41’, ‘cg42’, ‘cg43’, ‘cg44’, ‘cg45’, ‘cg46’, ‘cg47’, ‘cg48’, ‘cg49’, ‘cg50’, ‘cg51’, ‘cg52’, ‘cg53’, ‘cg54’, ‘cg55’, ‘cg56’, ‘cg57’, ‘cg58’, ‘cg59’, ‘cg60’, ‘cg61’, ‘cg62’, ‘cg63’, ‘cg64’, ‘cg65’, ‘cg66’, ‘cg67’, ‘cg68’, ‘cg69’, ‘cg70’, ‘cg71’, ‘cg72’, ‘cg73’, ‘cg74’, ‘cg75’, ‘ch01’, ‘ch02’, ‘ch03’, ‘ch04’, ‘ch05’, ‘ch06’, ‘ch07’, ‘ch08’, ‘ch09’, ‘ch10’, ‘ch11’, ‘ch12’, ‘ch13’, ‘ch14’, ‘ch15’, ‘ch16’, ‘ch17’, ‘ch18’, ‘ch19’, ‘ch20’, ‘ch21’, ‘ch22’, ‘ch23’, ‘ch24’, ‘ch25’, ‘ch26’, ‘ch27’, ‘ch28’, ‘ch29’, ‘ch30’, ‘cj01’, ‘cj02’, ‘cj03’, ‘cj04’, ‘cj05’, ‘cj06’, ‘cj07’, ‘cj08’, ‘cj09’, ‘cj10’, ‘cj11’, ‘cj12’, ‘cj13’, ‘cj14’, ‘cj15’, ‘cj16’, ‘cj17’, ‘cj18’, ‘cj19’, ‘cj20’, ‘cj21’, ‘cj22’, ‘cj23’, ‘cj24’, ‘cj25’, ‘cj26’, ‘cj27’, ‘cj28’, ‘cj29’, ‘cj30’, ‘cj31’, ‘cj32’, ‘cj33’, ‘cj34’, ‘cj35’, ‘cj36’, ‘cj37’, ‘cj38’, ‘cj39’, ‘cj40’, ‘cj41’, ‘cj42’, ‘cj43’, ‘cj44’, ‘cj45’, ‘cj46’, ‘cj47’, ‘cj48’, ‘cj49’, ‘cj50’, ‘cj51’, ‘cj52’, ‘cj53’, ‘cj54’, ‘cj55’, ‘cj56’, ‘cj57’, ‘cj58’, ‘cj59’, ‘cj60’, ‘cj61’, ‘cj62’, ‘cj63’, ‘cj64’, ‘cj65’, ‘cj66’, ‘cj67’, ‘cj68’, ‘cj69’, ‘cj70’, ‘cj71’, ‘cj72’, ‘cj73’, ‘cj74’, ‘cj75’, ‘cj76’, ‘cj77’, ‘cj78’, ‘cj79’, ‘cj80’, ‘ck01’, ‘ck02’, ‘ck03’, ‘ck04’, ‘ck05’, ‘ck06’, ‘ck07’, ‘ck08’, ‘ck09’, ‘ck10’, ‘ck11’, ‘ck12’, ‘ck13’, ‘ck14’, ‘ck15’, ‘ck16’, ‘ck17’, ‘ck18’, ‘ck19’, ‘ck20’, ‘ck21’, ‘ck22’, ‘ck23’, ‘ck24’, ‘ck25’, ‘ck26’, ‘ck27’, ‘ck28’, ‘ck29’, ‘cl01’, ‘cl02’, ‘cl03’, ‘cl04’, ‘cl05’, ‘cl06’, ‘cl07’, ‘cl08’, ‘cl09’, ‘cl10’, ‘cl11’, ‘cl12’, ‘cl13’, ‘cl14’, ‘cl15’, ‘cl16’, ‘cl17’, ‘cl18’, ‘cl19’, ‘cl20’, ‘cl21’, ‘cl22’, ‘cl23’, ‘cl24’, ‘cm01’, ‘cm02’, ‘cm03’, ‘cm04’, ‘cm05’, ‘cm06’, ‘cn01’, ‘cn02’, ‘cn03’, ‘cn04’, ‘cn05’, ‘cn06’, ‘cn07’, ‘cn08’, ‘cn09’, ‘cn10’, ‘cn11’, ‘cn12’, ‘cn13’, ‘cn14’, ‘cn15’, ‘cn16’, ‘cn17’, ‘cn18’, ‘cn19’, ‘cn20’, ‘cn21’, ‘cn22’, ‘cn23’, ‘cn24’, ‘cn25’, ‘cn26’, ‘cn27’, ‘cn28’, ‘cn29’, ‘cp01’, ‘cp02’, ‘cp03’, ‘cp04’, ‘cp05’, ‘cp06’, ‘cp07’, ‘cp08’, ‘cp09’, ‘cp10’, ‘cp11’, ‘cp12’, ‘cp13’, ‘cp14’, ‘cp15’, ‘cp16’, ‘cp17’, ‘cp18’, ‘cp19’, ‘cp20’, ‘cp21’, ‘cp22’, ‘cp23’, ‘cp24’, ‘cp25’, ‘cp26’, ‘cp27’, ‘cp28’, ‘cp29’, ‘cr01’, ‘cr02’, ‘cr03’, ‘cr04’, ‘cr05’, ‘cr06’, ‘cr07’, ‘cr08’, ‘cr09’]
3.4 總統就職演講 Inaugural
包含 1789 年以來所有美國總統就職演講文本;雖不是“最長”,但跨度時間大、適合語言演變分析, 屬于長句子語料。
注:該數據集無分類標簽 (categories)
-
數據信息
- 新聞數量 (Total documents): 60
- 總詞數 (Total tokens): 156,288
- 總句數 (Sentences): 5,395
- 詞匯量: 10,200
- 平均句長: 28.97 個單詞
- 最常見tokens:(‘the’, 9670), (‘,’, 7499), (‘of’, 7260), (‘and’, 5356)。
- 常見搭配:無。
- 包含 “God” 的句子:108 句。
-
文件名
文件名包含《年齡》和《姓名》兩個信息:
[‘1789-Washington.txt’, ‘1793-Washington.txt’, ‘1797-Adams.txt’, ‘1801-Jefferson.txt’, ‘1805-Jefferson.txt’, ‘1809-Madison.txt’, ‘1813-Madison.txt’, ‘1817-Monroe.txt’, ‘1821-Monroe.txt’, ‘1825-Adams.txt’, ‘1829-Jackson.txt’, ‘1833-Jackson.txt’, ‘1837-VanBuren.txt’, ‘1841-Harrison.txt’, ‘1845-Polk.txt’, ‘1849-Taylor.txt’, ‘1853-Pierce.txt’, ‘1857-Buchanan.txt’, ‘1861-Lincoln.txt’, ‘1865-Lincoln.txt’, ‘1869-Grant.txt’, ‘1873-Grant.txt’, ‘1877-Hayes.txt’, ‘1881-Garfield.txt’, ‘1885-Cleveland.txt’, ‘1889-Harrison.txt’, ‘1893-Cleveland.txt’, ‘1897-McKinley.txt’, ‘1901-McKinley.txt’, ‘1905-Roosevelt.txt’, ‘1909-Taft.txt’, ‘1913-Wilson.txt’, ‘1917-Wilson.txt’, ‘1921-Harding.txt’, ‘1925-Coolidge.txt’, ‘1929-Hoover.txt’, ‘1933-Roosevelt.txt’, ‘1937-Roosevelt.txt’, ‘1941-Roosevelt.txt’, ‘1945-Roosevelt.txt’, ‘1949-Truman.txt’, ‘1953-Eisenhower.txt’, ‘1957-Eisenhower.txt’, ‘1961-Kennedy.txt’, ‘1965-Johnson.txt’, ‘1969-Nixon.txt’, ‘1973-Nixon.txt’, ‘1977-Carter.txt’, ‘1981-Reagan.txt’, ‘1985-Reagan.txt’, ‘1989-Bush.txt’, ‘1993-Clinton.txt’, ‘1997-Clinton.txt’, ‘2001-Bush.txt’, ‘2005-Bush.txt’, ‘2009-Obama.txt’, ‘2013-Obama.txt’, ‘2017-Trump.txt’, ‘2021-Biden.txt’, ‘2025-Trump.txt’]
- 統計總統的演講次數
- 代碼
#統計每位總統的演講次數
from collections import Counter
from nltk.corpus import inaugural
presidents = [fileid.split('-')[1].replace('.txt', '') for fileid in inaugural.fileids()]
president_counts = Counter(presidents)
print(president_counts)
- 結果
Counter({‘Roosevelt’: 5, ‘Bush’: 3, ‘Washington’: 2, ‘Adams’: 2, ‘Jefferson’: 2, ‘Madison’: 2, ‘Monroe’: 2, ‘Jackson’: 2, ‘Harrison’: 2, ‘Lincoln’: 2, ‘Grant’: 2, ‘Cleveland’: 2, ‘McKinley’: 2, ‘Wilson’: 2, ‘Eisenhower’: 2, ‘Nixon’: 2, ‘Reagan’: 2, ‘Clinton’: 2, ‘Obama’: 2, ‘Trump’: 2, ‘VanBuren’: 1, ‘Polk’: 1, ‘Taylor’: 1, ‘Pierce’: 1, ‘Buchanan’: 1, ‘Hayes’: 1, ‘Garfield’: 1, ‘Taft’: 1, ‘Harding’: 1, ‘Coolidge’: 1, ‘Hoover’: 1, ‘Truman’: 1, ‘Kennedy’: 1, ‘Johnson’: 1, ‘Carter’: 1, ‘Biden’: 1})
- 統計詞匯出現的情況
統計三個詞匯:
‘freedom’, ‘china’, ‘democracy’
- 代碼
#繪制詞匯隨時間的變化(NLTK 自帶示例)
import matplotlib.pyplot as plt
from nltk.corpus import inaugural
from nltk import FreqDist
# 組織成 {年份: FreqDist對象}
cfd = nltk.ConditionalFreqDist((target, fileid[:4])for fileid in inaugural.fileids()for target in ['freedom', 'china', 'democracy']if target in inaugural.words(fileid))
cfd.plot(title='Keyword frequency in Inaugural Addresses')
- 結果
3.5網絡體文本 webtext
包含瀏覽器的爬蟲文本、如電影評論等,該數據無標簽(categories)
-
數據信息
- 新聞數量 (Total documents): 6
- 總詞數 (Total tokens): 396,733
- 總句數 (Sentences): 25,728
- 詞匯量: 21,538
- 平均句長: 15.42 個單詞
- 最常見tokens:(‘:’, 11501), (‘.’, 10530), (‘,’, 8668), (“'”, 8058)。
- 常見搭配:無。
- 包含 “God” 的句子:143 句。
-
文件名:
[‘firefox.txt’, ‘grail.txt’, ‘overheard.txt’, ‘pirates.txt’, ‘singles.txt’, ‘wine.txt’]
文件名 | 內容描述 |
---|---|
firefox.txt | Mozilla Firefox 瀏覽器論壇討論 |
grail.txt | 《Monty Python and the Holy Grail》電影劇本 |
overheard.txt | 紐約地鐵上的對話(Overheard in NYC) |
pirates.txt | 《加勒比海盜》電影評論 |
singles.txt | 網絡約會論壇發帖 |
wine.txt | 葡萄酒評論 |
- 找出長詞
- 代碼
long_words = [w for w in set(webtext.words('pirates.txt')) if len(w) > 10]
print(sorted(long_words)[:20]) # 按字母排序取前20個
- 結果
[‘Complications’, ‘Fortunately’, ‘HEADQUARTERS’, ‘Proceededly’, ‘QUARTERMASTER’, ‘Scandinavian’, ‘Scandinavians’, ‘Technically’, ‘Unfortunately’, ‘accidentally’, ‘acquaintance’, ‘altercation’, ‘approaching’, ‘calculations’, ‘camouflaged’, ‘candleholder’, ‘circumstance’, ‘circumstances’, ‘confronting’, ‘consciousness’
檢索關鍵詞的上下文
查看firefox中browser的上下文:
- 代碼
text = nltk.Text(webtext.words('firefox.txt'))
text.concordance("browser", width=60)
- 結果
Displaying 25 of 484 matches:
trl - N should open a new browser when only download dialog
tab should switch tabs in browser favicon . ico colors rend[ cust ] cancel is buggy Browser is ignoring the attibute
mark Add View -> Sidebars Browser Crash icons for customize
x is checking for default browser NO is missing from the buwhen closing main window browser long password can ' t wor
orts are not reflected in browser window url drop - down bothe download manager the browser crashes if you open the l
ron appears when starting browser Tab prefs should allow chopening View page Source browser opened from About Phoenixfor changing behavior of browser windows reusage Extension
fic Google search freezes browser . Open a bookmark folder
flow only cares about the browser border . Bookmark propert
ory consumption increases Browser fails to display the correxternal sources in open browser implement restore previou
ment bookmark icon causes browser lock up Java Plug - in st
ascript from resizing the browser crash upon clicking a lin
a . tar extension Closing browser from File Menu closes allPhoenix crashes in forum Browser locked if timeout during build under BeOS setting browser . urlbar . autoFill does
nal bookmarks ( stacked ) Browser hangs with flash plugin w
doesn ' t focus searchbar Browser crashes when pointer on m
solution favicons lost on browser shutdown + restart histor
ookmark Manager Crash the browser on loading if " reject po
Save Link As ..." crashes browser . Add context menu to boo
4.Ref
- https://www.nltk.org/data.html
- https://github.com/nltk/nltk
- https://www.gutenberg.org/files/36132/36132-h/36132-h.htm
- https://blog.csdn.net/weixin_40425640/article/details/124033677
- https://blog.csdn.net/2201_75499313/article/details/128355707