import nltk
from nltk.corpus import *
##古腾堡语料库---gutenberg
# print(nltk.corpus.gutenberg.fileids())
# emma = nltk.corpus.gutenberg.words('austen-emma.txt')
# print(len(emma))
#
# emma = nltk.Text(nltk.corpus.gutenberg.words('austen-emma.txt'))
# print(emma.concordance("surprise"))
#计算统计每个文本
#raw函数把文本中的内容以字符为单位分开,words函数把文本中的内容以单词为单位分开,sents(sentences)函数把文本中的内容以句子为单位分开。
# for f in gutenberg.fileids():
# num_chars = len(gutenberg.raw(f))
# num_words = len(gutenberg.words(f))
# num_sents = len(gutenberg.sents(f))
# num_vocab = len(set([w.lower() for w in gutenberg.words(f)]))
# print(int(num_chars/num_words),int(num_words/num_sents),int(num_words/num_vocab),f)
#sents()函数把文本划分成句子,其中每一个句子是一个词链表。
# sentences = gutenberg.sents('shakespeare-macbeth.txt')
# print(sentences)
#网络和聊天文本
# chatroom=nps_chat.posts('10-19-20s_706posts.xml')
# print(chatroom[123])
#布朗语料库---brown
# print(brown.categories())
# print(brown.words(categories='news')
# print(brown.words(fileids=['cg22']))
# print(brown.sents(categories=['news', 'editorial', 'reviews']))
#产生特定文体的计数
# news_text = brown.words(categories='news')
# fdist = nltk.FreqDist([w.lower() for w in news_text])
# modals = ['can','could','may','might','must','will']
# for i in modals:
# print(i+':', fdist[i])
#NLTK 提供的带条件的频率分布函数-------为什么
# cfd = nltk.ConditionalFreqDist(
# (genre,word)
# for genre in brown.categories()
# for word in brown.words(categories=genre)
# )
# genres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor']
# modals = ['can', 'could', 'may', 'might', 'must', 'will']
# print(cfd.tabulate(conditions=genres,samples=modals))
#路透社语料库---reuters
# print(reuters.fileids()) #库所有的文件编号
# print(reuters.categories()) #库所有的种类
# print(reuters.categories('training/9865')) #指定文件编号的种类
# print(reuters.categories(['training/9865','training/9880']))#指定两个文件编号的种类
# print(reuters.fileids('barley')) #指定种类的文件编号,不用category='barley'
# print(reuters.fileids(['barley','corn']))
#以文档或类别为单位查找我们想要的词或句子。这些文本中最开始的几个词是标题,按照惯例以大写字母存储。
# print(reuters.words('training/9865')[:14])
# print(reuters.words(['training/9865','training/9880'])) #这个是要连续输出两个文件?
# print(reuters.words(categories='barley')) #需要标明categories
# print(reuters.words(categories=['barley','corn']))
#就职演讲语料库---inaugural
#条件频率分布图:计数就职演说语料库中所有以america 或citizen 开始的词。每个
#演讲单独计数。这样就能观察出随时间变化用法上的演变趋势
# print(inaugural.fileids())
# print([f[:4] for f in inaugural.fileids()]) #f[:4]提取每个文件中前四个字符即演讲年代
# cfd = nltk.ConditionalFreqDist(
# (target,file[:4])
# for file in inaugural.fileids()
# for w in inaugural.words(file)
# for target in ['america','citizen']
# if w.lower().startswith(target)
# )
# cfd.plot()
#标注文本语料库
#用条件频率分布来研究“世界人权宣言”(udhr)语料库中不同语言版本中的字长差异。
# print(udhr.fileids())
# languages = ['Chickasaw', 'English', 'German_Deutsch','Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik']
# cfd = nltk.ConditionalFreqDist(
# (lang,len(word))
# for lang in languages
# for word in udhr.words(lang + '-Latin1')
# )
# cfd.plot(cumulative = True)
#文本语料库的结构
#载入你自己的语料库
###### 条件频率分布 #####
#FreqDist(mylist)会计算链表中每个项目出现的次数
#当语料文本被分为几类(文体、主题、作者等)时,我们可以计算每个类别独立的频率分布。
#ConditionalFreqDist实现条件频率分布
#条件和事件
#text = ['The', 'Fulton', 'County', 'Grand', 'Jury', 'said']
#pairs = [('news', 'The'), ('news', 'Fulton'), ('news', 'County')]
#每对的形式是:(条件,事件)。如果我们按文体处理整个布朗语料库,将有15 个条件(每个文体一个条件)和1,161,192 个事件(每一个词一个事件)
#按文体计数词汇---brown
cfd = nltk.ConditionalFreqDist(
(genre,word)
for genre in ['news', 'romance'] #brown.categories()
for word in brown.words(categories = genre)
)
cfd.plot(cumulative = True) #(genre,word)画不出来
# genre_words = [
# (genre,word)
# for genre in ['news', 'romance'] #brown.categories()
# for word in brown.words(categories = genre)
# ]
# print(genre_words[:4])
# cfd = nltk.ConditionalFreqDist(genre_words)
# print(cfd.conditions())
# print(cfd['news']) #直接cfd['news']
# print(list(cfd['news'])) #打印出类别是news的words
# print(cfd['news']['The']) #打印出类别为news的词The的次数
#使用双连词生成随机文本
#bigrams()函数接受一个词汇链表,并建立一个连续的词对链表。
# sent = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven','and', 'the', 'earth', '.']
# print(list(nltk.bigrams(sent))) #必须外面加一个list
------------------------------------重点线,感觉很有用--------------------------------------------------
#例2-1. 产生随机文本:此程序获得《创世记》文本中所有的双连词,然后构造一个条件频率分
#布来记录哪些词汇最有可能跟在给定的词的后面
def generate_model(cfdist,word,num = 15):
for i in range(num):
print(word)
word = cfdist[word].max()
text = nltk.corpus.genesis.words('english-kjv.txt')
bigrams = nltk.bigrams(text)
cfd = nltk.ConditionalFreqDist(bigrams)
for i in list(cfd['living']):
print(i ,':',cfd['living'][i])
generate_model(cfd,'living')
运行结果:
creature : 7
thing : 4
soul : 1
. : 1
substance : 2
, : 1
living
creature
that
he
said
,
and
the
land
of
the
land
of
the
land
------------------------------------------------------------------------------------------------------------
#过滤文本:此程序计算文本的词汇表,然后删除所有在现有的词汇列表中出现的元素,只留下罕见或拼写错误的词。
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)
print(unusual_words(nltk.corpus.gutenberg.words('austen-sense.txt')))
print(unusual_words(nltk.corpus.nps_chat.words()))
#停用词语料库,那些高频词汇,如:the,to,停用词通常几乎没有什么词汇内容,而它们的出现会使区分文本变困难。
#stopwords
# print(stopwords.words('english'))
#定义一个函数来计算文本中没有在停用词列表中的词的比例。
def content_fraction(text):
stopwords=nltk.corpus.stopwords.words('english')
content=[w for w in text if w.lower() not in stopwords]
return len(content)/len(text)
print(content_fraction(nltk.corpus.reuters.words()))
#一个字母拼词谜题
#FreqDist比较法允许我们检查每个字母在候选词中的频率是否小于或等于相应的字母在拼词谜题中的频率。
# puzzle_letters=nltk.FreqDist('egivrvonl')
# obligatory='r'
# wordlist=nltk.corpus.words.words()
# print([w for w in wordlist if len(w)>=6
# and obligatory in w
# and nltk.FreqDist(w)<=puzzle_letters])
#名字语料库
#包括8000 个按性别分类的名字。男性和女性的名字存储在单独的文件中。让我们找出同时出现在两个文件中的名字
# femalename = nltk.corpus.names.words('female.txt')
# malename = nltk.corpus.names.words('male.txt')
# samename = [w for w in femalename if w in malename]
# print(samename)
#以字母a 结尾的名字几乎都是女性。条件概率分布
#name[-1]是name的最后一个字母
# cfd = nltk.ConditionalFreqDist(
# (fileid,name[-1])
# for fileid in nltk.corpus.names.fileids()
# for name in nltk.corpus.names.words(fileid)
# )
# cfd.plot()
#发音的词典
#NLTK 中包括美国英语的CMU 发音词典,它是为语音合成器使用而设计的。
entries = nltk.corpus.cmudict.entries()
# print(len(entries))
# for entry in entries[39943:39951]:
# print(entry)
#扫描词典中那些发音包含三个音素的条目且第一个和最后一个分别为P,T
for word,pron in entries:
if len(pron)==3:
ph1,ph2,ph3=pron
if ph1=='P' and ph3=='T':
print(word,ph2)
#使用内部的链表推导。这段程序找到所有发音结尾与nicks 相似的词汇。你可以使用此方法来找到押韵的词。
syllable = ['N','IHO','K','S']
print([word for word,pron in entries if pron[-4:]==syllable])