#寻找该文本中最常见的50个词 >>>fdist1=FreqDist(text1) >>>vocabulary1=fdist1.keys() >>>vocabulary1[:50] 报错:'dict_keys' object is not subscriptable #这是Python3才会出现的错误,需改成 >>>vocabulary1=list(fdist1.most_common(50)) >>>vocabulary1 #这样才能得到正确的结果,因为先前的vocabulary不能进行切片 #生成前频率最高的50个词的累计频率图 fdist1.plot(50,cumulative=True) #列出只出现了一次的词 fdist1.hapaxes()
细粒度的选择词 设性质P:一个超过15个字符的词,V代表这个词汇表 a. {w | w ∈ V & P(w)} b. [w for w in V if p(w)]
1 2 3 4 5 6 7
#筛选出该文本v中的超过15个字符的 v=set(text1) long_words=[w for w in v if len(w) >15 ] sorted(long_words)#排序,发现大写在前,小写在后 #筛选出该文本中的长低频词 >>>fidst5=FreqDist(text5) >>> sorted([w for w in set(text5) if len(w)>7 and fidst5[w]>7])
#创造一个列表,其中每个数字是文本中对应词的长度 >>>[len(w) for w in text1] >>>fdist=FreqDist([len(w) for w in text1]) >>>fdist #以频率递减顺序排序的样本列表 >>>fdist.keys() #(长度,频率) >>>fdist.items() #最大频率的长度 >>>fdist.max() #长度为3的词在全书单词中的频率 >>>fdist.freq(3) #增加样本 >>>fdist.inc(sample) #样本总数 >>>fdist.N() #频率分布表 >>>fdist.tabulate() #测试样本在fdist1中出现的频率是否小于fdist2 fdist1<fdist2
[w for w in sent7 if len(w) < 4] #其中, <可以换成其他条件符号 [w for w in text if condition] #测试s是否以t开头 s.startswith(t) #测试s是否以t结尾 s.endswith(t) #测试s是否包含t t in s #测试s是否所有字符都是小写字母 s.islower() #测试s是否所有字符都是大写字母 s.isupper() #测试s是否所有字符都是字母 s.isalpha() #测试s是否所有字符都是字母或数字 s.isalnum() #测试s是否所有字符都是数字 s.isdigit() #测试s是否所有字符都是首字母大写 s.istitle()
文本中选择词汇运算符
1 2 3 4 5 6 7 8
>>>sorted([w for w in set(text1) if w.endswith('ableness')]) >>>sorted([item for item in set(sent7) if item.isdigit()]) >>>sorted([item for item in set(text6) if item.istitle()]) >>>sorted([term for term in set(text4) if 'gnt' in term]) >>>sorted([w for w in set(text7) if '-' in w and 'index' in w]) >>>sorted([wd for wd in set(text3) if wd.istitle() and len(wd)]) >>>sorted([t for t in set(text2) if 'cie' in t or 'cei' in t]) >>>sorted([t for t in set(sent7) if not t.islower()])
条件循环
1 2 3 4
for word in ['Call','me','Ishmael','.']: print(word) for word in tricky: print(word,end=',')
1.5自动理解自然语言 词义消歧:推算出特定上下文中的词被赋予的意思。 指代消解(anaphora resolution):检测主语和动词的宾语的计算技术。 语义角色标注(semantic role labeling):确定名词短语如何与动词相关联。 自动生成语言:例如自动问答和机器翻译。 文本对齐:给出一个双语文档,自动配对组成句子的过程。
1 2 3 4 5 6
Q1: name 'babelize_shell' is not defined A1:The issue isn't with your code. The problem is that the babelfish translation service is no longer in operation so the example code no longer works. #原始的对话系统 nltk.chat.chatbots()
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') for fileid in gutenberg.fileids(): num_chars=len(gutenberg.raw(fileid)) num_words=len(gutenberg.words(fileid)) num_sents=len(gutenberg.sents(fileid)) num_vocab=len(set([w.lower() for w in gutenberg.words(fileid)])) print(int(num_chars/num_words),int(num_words/num_sents),int(num_words/num_vocab)) #sents()函数分割句子 macbeth_sentences=gutenberg.sents('shakespeare-macbeth.txt') #访问句子 macbeth_sentences[1037] #找最长的句子 longest_len=max([len(s) for s in macbeth_sentences]) [s for s in macbeth_sentences if len(s) == longest_len] #“原始”的文本 len(gutenberg.raw('blake-poems.txt') #网络聊天文本 import nltk from nltk.corpus import webtext for fileid in webtext.fileids(): print(fileid,webtext.raw(fileid)[:65],'...') from nltk.corpus import nps_chat #2006年10月19日20岁聊天室手机的706个帖子 chatroom=nps_chat.posts('10-19-20s_706posts.xml') chatroom[123] #布朗语料库 from nltk.corpus import brown #布朗语料库的分类 brown.categories() #输入对应的File_id,访问对应的文件 brown.words(fileids=['cg22']) #三个类型的sents brown.sents(categories=['news','editorial','reviews']) new_text=brown.words(categories='news') cfd=nltk.ConditionalFreqDist((genre,word) for genre in brown.categories() for word in brown.words(categories=genre)) genres=['news','religion','hobbies','science_fiction','romantic','humor'] modals=['can','could','may','might','must','will'] #不同类型文章下的形态动词频率分布图 cfd.tabulate(conditions=genres,samples=modals) #路透社语料库 from nltk.corpus import reuters #查看路透社全部主题的文件名 reuters.fileids() #查看路透社某主题的文件名 reuters.fileids('barley') #查看路透社某几个主题的文件名 reuters.fileids(['barley','corn']) #查看路透社的文章的类别下的文档 reuters.categories() reuters.categories('training/9865') reuters.categories(['training/9865','training/9880']) #根据类别看文档内容 reuters.words(['training/9865','training/9880']) reuters.words(categories=['barley','corn']) #就职演说语料库 from nltk.corpus import inaugural inaugural.fileids() [fileids[:4] for fileids in inaugural.fileids()] from nltk.corpus import inaugural 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()
nltk.corpus.cess_esp.words() nltk.corpus.floresta.words() nltk.corpus.indian.words() #超过300种语言的世界人权宣言 nltk.corpus.udhr.fileids() nltk.corpus.udhr.words('Javanese-Latin1')[11:] #查看该文本的字母频率分布图 raw_text=udhr.raw('Yoruba-UTF8') nltk.FreqDist(raw_text).plot() #不同版本的世界人权宣言的累积字长条件频率分布图 from nltk.corpus import udhr languages = ["Chickasaw", "English", "German_Deutsch"] cfd = nltk.ConditionalFreqDist( (lang, len(word)) for lang in languages for word in udhr.words(lang+"-Latin1"))#文件编码是Latin1 cfd.plot(cumulative=True)
载入自己的语料库 from nltk.corpus import PlaintextCorpusReader corpus_root =r"C:\Users\Greenaway\Desktop\text-mining" wordlists=PlaintextCorpusReader(corpus_root,'.*') wordlists.fileids() wordlists.words('train.csv')
from nltk.corpus import BracketParseCorpusReader file_pattern=r".*.csv" ptb = BracketParseCorpusReader(corpus_root, file_pattern) ptb.fileids()
条件频率分布:是频率分布的集合,每个频率分布有一个不同的条件。
条件和事件:不是处理一个词序列,而是处理一个配对序列 按文体计数词汇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from nltk.corpus import brown cfd=nltk.ConditionalFreqDist( (genre,word) for genre in brown.categories() for word in brown.words(categories=genre)) genre_word=[(genre,word) for genre in ['news','romance'] for word in brown.words(categories=genre)] len(genre_word) genre_word[:4] genre_word[-4]
from nltk.corpus import inaugural cfd=nltk.ConditionalFreqDist( (atrget,fileid[:4]) for fileid in inaugural.fileids() for w in inaugural.words(fileid) for target in ['america','citizen'] if w.lower().startswith(target) )
from nltk.corpus import udhr languages=['Chickasaw','English'] cfd=nltk.ConditionalFreqDist( (lang,len(word)) for lang in languages for word in udhr.words(lang+'-Latin1') )
sent=['In','the','beginning','God','created','the','heaven','and','the','earth','.'] list(nltk.bigrams(sent)) 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)
#import A as B :这种方式为给引入的包A定义一个别名B from nltk.corpus import wordnet as wn #这样就不用输入wordnet了,定义了别名以后,原名就不能用了 #探索一个词的同义词: >>>wn.synsets('motorcar') [Synset('car.n.01')] #('car.n.01')被称为synset(同义词集)
Q1:wn.synset('car.n.01').lemma_names 出现了<bound method Synset.lemma_names of Synset('car.n.01')> A1:应改为 wn.synset('car.n.01').lemma_names()
#查询一个同义词集的定义 wn.synset('car.n.01').definition() #查询一个同义词集的例句 wn.synset('car.n.01').examples() #查询一个同义词集的所有词意的包(? wn.synset('car.n.01').lemmas() #查看一个同义词集的词集名 wn.lemma('car.n.01.automobile') #查看一个同义词集的上级词集名 wn.lemma('car.n.01.automobile').synset() #查看一个同义词集的当前级词集名 wn.lemma('car.n.01.automobile').name() #查看一个单词的所有释义的同义词集 wn.synsets('car') #输出每个释义下的同义词 for synset in wn.synsets('car'): print(synset.lemma_names())
import re wordlist=[w for w in nltk.corpus.words.words('en') if w.islower()] #re.search(p,s)检查字符串s中是否有模式p #比如检测单词是否以ed结尾 [w for w in wordlist if re.search('ed$',w)] # ^表示一定是这么长的字符,且j是第3个,t是倒数第3个字符 [w for w in wordlist if re.search('^..j..t..$',w)] #去掉$,j是第3个,t无所谓 [w for w in wordlist if re.search('^..j..t..',w)] #去掉^,t是第3个,j无所谓 [w for w in wordlist if re.search('..j..t..$',w)] #去掉^和$只要包含j 和 t就行,两个字母的先后无所谓 [w for w in wordlist if re.search('..j..t..',w)] #4个字符分别从四个[]中选择,并且按照[]先后顺序 [w for w in wordlist if re.search('^[ghi][mno][jlk][def]$',w)] #在wordlist中 由g到o组成的长短不一的单词 [w for w in wordlist if re.search('^[g-o]+$',w)] #在wordlist中 由a-f j-o 中的至少1个字母组成的长短不一的单词 [w for w in wordlist if re.search('^[a-gj-o]+$')]
chat_words=sorted(set(w for w in nltk.corpus.nps_chat.word())) #在chat_words 中 严格包含这四个字母的单词 [w for w in chat_words if re.search('^m+i+n+e+$',w)] #在chat_words 中 含有 m i n e中的一个或没有的单词(所有元素) [w for w in chat_words if re.search('^m*i*n*e*$',w)] #在chat_words 中 含有至少h a中的一个字母的单词 [w for w in chat_words if re.search('^[ha]+$',w)]
wsj=sorted(set(nltk.corpus.treebank.words())) #\. 为转义字符,避免混淆 #逗号左侧和逗号右侧的字符必须由0-9之间的数字组成的所有元素,长度不定 [w for w in wsj if re.search('^[0-9]+\.[0-9]+$',w)] #在wsj中由A-Z且后缀为$的所有元素 [w for w in wsj if re.search('^[A-Z]+\$$',w)] #在wsj中仅仅由0-9之间的数字组成且长度严格为4的元素 [w for w in wsj if re.search('^[0-9]{4}$',w)] #在wsj中被-分割的 前半部分由0-9长度不定的字符串, #后半部分由长度在3-5之间的a-z组成的单词的所有元素 [w for w in wsj if re.search('^[0-9]+-[a-z]{3,5}',w)] #被-分割成三部分的长度分别 ≥5, 2或3,≤6 的字母串的所有元素 [w for w in wsj if re.search('^[a-z]{5,}-[a-z]{2,3}-[a-z]{,6}$',w)] #ing或ed结尾的单词 [w for w in wsj if re.search('(ed|ing)',w)]
word='supercalifragilisticexpialidocious' re.findall(r'[aeiou]',word) fd=nltk.FreqDist(vs for word in wsj) for vs in findall(r'[aeiou]{2,}',word) fd.items()
#将2009-12-31转化成2009.12.31 [int(n) for n in re.findall(r'[0-9]+','2009-12-31')] #消除前几个元音字母 regexp=r'^[AEIOUaeiou]+|[AEIOUaeiou]+$|[^AEIOUaeiou]' # def compress(word): pieces=re.findall(regexp,word) return ''.join(pieces) english_udhr=nltk.corpus.udhr.words('English-Latin1') print(nltk.tokenwrap(compress(w) for w in english_udhr[:75]))
raw = “””DENNIS: Listen, strange women lying in ponds distributing swords is no basis for a system of government. Supreme executive powe r derives from a mandate from the masses, not from some farcical aquat ic ceremony.””” tokens=nltk.word_tokenize(raw) [porter.stem(t) for t in tokens] [lancaster.stem(t) for t in tokens]
Porter词干提取器 class IndexedText(object): def init(self, stemmer, text): self._text = text self._stemmer = stemmer self._index = nltk.Index((self._stem(word), i) for (i, word) in enumerate(text)) def concordance(self, word, width=40): key = self._stem(word) wc = width/4 # words of context for i in self._index[key]: lcontext = ‘ ‘.join(self._text[i-wc:i]) rcontext = ‘ ‘.join(self._text[i:i+wc]) ldisplay = ‘%*s’ % (width, lcontext[-width:]) rdisplay = ‘%-*s’ % (width, rcontext[:width]) print ldisplay, rdisplay def _stem(self, word): return self._stemmer.stem(word).lower()