古腾堡项目的其它文本可以在线获得,
整个过程大概需要几十秒(实验室网络不行是硬伤)
使用raw()可以得到原始的字符串。但是raw得到的数据绝对不是我们能直接拿去分析的,还要经过一些预处理。我们要将字符串分解为词和标点符号,正如我们在第1章中所看到的。这一步被称为分词,它产生我们所熟悉的结构,一个词汇和标点符号的链表。
好像很多公测语料都是html或者xml发布的,这个应该可以处理类似的数据。但书里说其中仍然含有不需要的内容,包括网站导航及有关报道等,通过一些尝试和出错你可以找到内容索引的开始和结尾,并选择你感兴趣的标识符,按照前面讲的那样初始化一个文本。
这里面的“尝试和出错”有点不合适吧。难道不能按标签去找吗,写一个网页模版然后去抽取某基础标签的内容,之前都是这么干的。
网络可以被看作未经标注的巨大的语料库。网络搜索引擎提供了一个有效的手段,搜索大量文本作为有关的语言学的例子。搜索引擎的主要优势是规模:因为你正在寻找这样庞大的一个文件集,会更容易找到你感兴趣语言模式。而且,你可以使用非常具体的模式,仅在较小的范围匹配一两个例子,但在网络上可能匹配成千上万的例子。网络搜索引擎的第个优势是非常容易使用。因此,它是一个非常方便的工具,可以快速检查一个理论是否合理。
我觉得这个部分可以使用爬虫和html处理来解决,更加方便。
只需要注意一点,使用”\\”就没问题的。path2='D:\\PythonSource\\fileTest.txt'
ASCII码文本和HTML文本是人可读的格式。文字常常以二进制格式出现,如PDF和MSWord,只能使用专门的软件打开。第三方函数库如pypdf和pywin32提供了对这些格式的访问。从多列文档中提取文本是特别具有挑战性的。一次性转换几个文件,会比较简单些,用一个合适的应用程序打开文件,以文本格式保存到本地驱动器,然后以如下所述的方式访问它。如果该文档已经在网络上,你可以在Google的搜索框输入它的URL。搜索结果通常包括这个文档的HTML版本的链接,你可以将它保存为文本。
Python2.X的版本是s=raw_input("Entersometext:"),到了3.X好像是用input代替了raw_input,更加好记了。
这个图表示的很清楚,我觉得预处理的任务就是将非结构化的数据尽量结构化,以便进一步处理。
又想起那个关于四六级的笑话了,话说学渣背单词,从前往后背,背不过C,从后往前背,背不过S。看来得说从前往后背,背不过e,从后往前背,背不过t,这样才更科学。
主要是列表切片和find,很简单。
p100有详情。师兄温馨提示我,split和strip非常重要,尤其是strip和Java里的trim一样,处理文本数据经常需要去掉字符串前后的空格什么的,没有会很麻烦。
当我们在一个Python程序中打开并读入一个文件,我们得到一个对应整个文件内容的字符串。如果我们使用一个for循环来处理这个字符串元素,所有我们可以挑选出的只是单
个的字符——我们不选择粒度。相比之下,链表中的元素可以很大也可以很小,只要我们喜欢。例如:它们可能是段落、句子、短语、单词、字符。所以,链表的优势是我们可以灵活的决定它包含的元素,相应的后续的处理也变得灵活。因此,我们在一段NLP代码中可能做的第一件事情就是将一个字符串分词放入一个字符串链表中。相反,当我们要将结果写入到一个文件或终端,我们通常会将它们格式化为一个字符串。
字符串是不可变的:一旦你创建了一个字符串,就不能改变它。然而,链表是可变的,其内容可以随时修改。作为一个结论,链表支持修改原始值的操作,而不是产生一个新的值。
Unicode支持超过一百万种字符。每个字符分配一个编号,称为编码点。文件中的文本都是有特定编码的,所以我们需要一些机制来将文本翻译成Unicode翻译成Unicode叫做解码。相对的,要将Unicode写入一个文件或终端,我们首先需要将Unicode转化为合适的编码——这种将Unicode转化为其它编码的过程叫做编码.
P108正则表达式都是差不多的,pythonli里的,java里的,shell里的都差不多。
T9系统用于在手机上输入文本。两个或两个以上的词汇以相同的击键顺序输入,这叫做输入法联想提示,这个原来是这样的啊。那么在用户词库里的应该优先权更大一点,这样就符合个性化的要求。
这表明另一个微妙之处:“*”操作符是“贪婪的”,所以表达式的“.*”部分试图尽可能多的匹配输入的字符串。
regexp=r'^(.*)(ing|ly|ed|ious|ies|ive|es|s|ment)$'
^abc表示以abc开始
如果我们要使用括号来指定连接的范围,但不想选择要输出的字符串,必须添加“:”
这个在做商品评价什么的应该非常有用的,直接抽取附近的形容词然后统计所占比例就可以了。
去掉所有的词缀以及提取词干的任务等。更进一步的步骤是确保结果形式是字典中确定的词,即叫做词形归并的任务。
NLTK中包括了一些现成的词干提取器,Porter和Lancaster词干提取器按照它们自己的规则剥离词缀。NltkTest105.TokenerCompare试了一下,好像是Porter好一些。虽说专业的比较好,但是据说nltk的预处理也就一般,英文的还是一般用Stanford的,可以试着比较一下。
WordNet词形归并器删除词缀产生的词都是在它的字典中的词。这个额外的检查过程使词形归并器比刚才提到的词干提取器要慢。
好吧,确实很慢,大概慢一倍以上,不过还是可以接收的,可以考虑和Porter级联使用。
分词是将字符串切割成可识别的构成一块语言数据的语言单元。
函数nltk.regexp_tokenize()与re.findall()类似(我们一直在使用它进行分词)。然而,nltk.regexp_tokenize()分词效率更高,且不需要特殊处理括号。
个人觉得,如果不是专业研究分词,可以简单的使用目前已公认的效果最好的分词工具就可以了,不必要为了造飞机去研究冶铁。
在将文本分词之前,我们需要将它分割成句子。NLTK通过包含Punkt句子分割器(Kiss&Strunk,2006)简化了这些。
现在分词的任务变成了一个搜索问题:找到将文本字符串正确分割成词汇的字位串。我们假定学习者接收词,并将它们存储在一个内部词典中。给定一个合适的词典,是能够由词典中的词的序列来重构源文本的。
好吧,默默的在这里决定了,英文用Stanford的分词,中文用NLPIR2014,不在这里纠结了。
''.join(silly)
太基础了,不多说
%s和%d。我们也可以指定宽度,如%6s,产生一个宽度为6的字符串。
我们可以在Python的textwrap模块的帮助下采取换行。
NLTK在使用Python处理自然语言的工具中处于领先的地位。它提供了WordNet这种方便处理词汇资源的接口,以及分类、分词、词干提取、标注、语法分析、语义推理等类库。
安装NLTK:sudopipinstall-Unltk
安装Numpy(可选):sudopipinstall-Unumpy
安装测试:pythonthentypeimportnltk
Pattern拥有一系列的自然语言处理工具,比如说词性标注工具(Part-Of-SpeechTagger),N元搜索(n-gramsearch),情感分析(sentimentanalysis),WordNet。它也支持机器学习的向量空间模型,聚类,向量机。
pipinstallpattern
TextBlob是一个处理文本数据的Python库。它提供了一个简单的api来解决一些常见的自然语言处理任务,例如词性标注、名词短语抽取、情感分析、分类、翻译等等。
pipinstall-Utextblob
Gensim是一个Python库,用于对大型语料库进行主题建模、文件索引、相似度检索等。它可以处理大于内存的输入数据。作者说它是“纯文本上无监督的语义建模最健壮、高效、易用的软件。”
网站:
安装:
pipinstall-Ugensim
LInux:sudoapt-getinstallpymol
Fedora:yuminstallpymol
这是一个商业的开源软件。结合了Python和Cython优异的NLP工具。是快速的,最先进的自然语言处理工具。
pipinstallspacy
Polyglot支持大规模多语言应用程序的处理。它支持165种语言的分词,196中语言的辨识,40种语言的专有名词识别,16种语言的词性标注,136种语言的情感分析,137种语言的嵌入,135种语言的形态分析,以及69种语言的翻译。
pipinstallpolyglot
Quepy是一个Python框架,提供了将自然语言问题转换成为数据库查询语言中的查询。它可以方便地自定义自然语言中不同类型的问题和数据库查询。所以,通过Quepy,仅仅修改几行代码,就可以构建你自己的自然语言查询数据库系统。
NLTK模块及功能介绍
我的Python版本是2.7.5,NLTK版本2.0.4
2.安装Pip:运行sudoeasy_installpip(一定要以root权限运行)
3.安装Numpy(optional):运行sudopipinstall-Unumpy
4.安装NLTK:运行sudopipinstall-Unltk
5.进入python,并输入以下命令
最后在Python目录运行以下命令以及结果,说明安装已成功
concordance:搜索text1中的monstrous
1>>>text1.similar("monstrous")2Buildingword-contextindex...3abundantcandidcarefulchristiancontemptiblecuriousdelightfully4determineddolefuldomineeringexasperatefearlessfewgamesome5horribleimpalpableimperiallamentablelazylovingdispersion_plot:用离散图判断词在文本的位置即偏移量
1>>>text4.dispersion_plot(["citizens","democracy","freedom","duties","America"])
1>>>sent12['Call','me','Ishmael','.']3>>>sorted(sent1)4['.','Call','Ishmael','me']3.3频率分布nltk.probability.FreqDist
2.指代消解
3.自动生成语言
4.机器翻译
5.人机对话系统
6.文本的含义
虽然是初次接触Python,NLTK,但是我已经觉得他们的好用以及方便,接下来就会深入的学习他们。
5.2TaggedCorpora标注语料库
RepresentingTaggedTokens表示标注的语言符号
ByconventioninNLTK,ataggedtokenisrepresentedusingatupleconsistingofthetokenandthetag.Wecancreateoneofthesespecialtuplesfromthestandardstringrepresentationofataggedtoken,usingthefunctionstr2tuple():
>>>tagged_token=nltk.tag.str2tuple('fly/NN')
>>>tagged_token
('fly','NN')
>>>tagged_token[0]
'fly'
>>>tagged_token[1]
'NN'
Wecanconstructalistoftaggedtokensdirectlyfromastring.Thefirststepistotokenizethestringtoaccesstheindividualword/tagstrings,andthentoconverteachoftheseintoatuple(usingstr2tuple()).
>>>sent='''
...The/ATgrand/JJjury/NNcommented/VBDon/INa/ATnumber/NNof/IN
...other/APtopics/NNS,/,AMONG/INthem/PPOthe/ATAtlanta/NPand/CC
...Fulton/NP-tlCounty/NN-tlpurchasing/VBGdepartments/NNSwhich/WDTit/PPS
...said/VBD``/``ARE/BERwell/QLoperated/VBNand/CCfollow/VBgenerally/RB
...accepted/VBNpractices/NNSwhich/WDTinure/VBto/INthe/ATbest/JJT
...interest/NNof/INboth/ABXgovernments/NNS''/''./.
...'''
>>>[nltk.tag.str2tuple(t)fortinsent.split()]
[('The','AT'),('grand','JJ'),('jury','NN'),('commented','VBD'),
('on','IN'),('a','AT'),('number','NN'),...('.','.')]
ReadingTaggedCorpora读取已标注的语料库
SeveralofthecorporaincludedwithNLTKhavebeentaggedfortheirpart-of-speech.Here'sanexampleofwhatyoumightseeifyouopenedafilefromtheBrownCorpuswithatexteditor:
The/atFulton/np-tlCounty/nn-tlGrand/jj-tlJury/nn-tlsaid/vbdFriday/nran/atinvestigation/nnof/inAtlanta's/np$recent/jjprimary/nnelection/nnproduced/vbd/no/atevidence/nn''/''that/csany/dtiirregularities/nnstook/vbdplace/nn./.
Othercorporauseavarietyofformatsforstoringpart-of-speechtags.NLTK'scorpusreadersprovideauniforminterfacesothatyoudon'thavetobeconcernedwiththedifferentfileformats.Incontrastwiththefileextractshownabove,thecorpusreaderfortheBrownCorpusrepresentsthedataasshownbelow.Notethatpart-of-speechtagshavebeenconvertedtouppercase,sincethishasbecomestandardpractice(标准惯例)sincetheBrownCorpuswaspublished.
>>>nltk.corpus.brown.tagged_words()
[('The','AT'),('Fulton','NP-TL'),('County','NN-TL'),...]
>>>nltk.corpus.brown.tagged_words(simplify_tags=True)
[('The','DET'),('Fulton','N'),('County','N'),...]
Wheneveracorpuscontainstaggedtext,theNLTKcorpusinterfacewillhaveatagged_words()method.Herearesomemoreexamples,againusingtheoutputformatillustratedfortheBrownCorpus:
>>>printnltk.corpus.nps_chat.tagged_words()
[('now','RB'),('im','PRP'),('left','VBD'),...]
>>>nltk.corpus.conll2000.tagged_words()
[('Confidence','NN'),('in','IN'),('the','DT'),...]
>>>nltk.corpus.treebank.tagged_words()
[('Pierre','NNP'),('Vinken','NNP'),(',',','),...]
Notallcorporaemploythesamesetoftags;seethetagsethelpfunctionalityandthereadme()methodsmentionedabovefordocumentation.Initiallywewanttoavoidthecomplicationsofthesetagsets,soweuseabuilt-inmappingtoasimplifiedtagset:
[('The','DET'),('Fulton','NP'),('County','N'),...]
>>>nltk.corpus.treebank.tagged_words(simplify_tags=True)
[('Pierre','NP'),('Vinken','NP'),(',',','),...]
TaggedcorporaforseveralotherlanguagesaredistributedwithNLTK,includingChinese,Hindi,Portuguese,Spanish,DutchandCatalan.Theseusuallycontainnon-ASCIItext,andPythonalwaysdisplaysthisinhexadecimalwhenprintingalargerstructuresuchasalist.
>>>nltk.corpus.sinica_treebank.tagged_words()
[('\xe4\xb8\x80','Neu'),('\xe5\x8f\x8b\xe6\x83\x85','Nad'),...]
>>>nltk.corpus.indian.tagged_words()
[('\xe0\xa6\xae\xe0\xa6\xb9\xe0\xa6\xbf\xe0\xa6\xb7\xe0\xa7\x87\xe0\xa6\xb0','NN'),
('\xe0\xa6\xb8\xe0\xa6\xa8\xe0\xa7\x8d\xe0\xa6\xa4\xe0\xa6\xbe\xe0\xa6\xa8','NN'),
...]
>>>nltk.corpus.mac_morpho.tagged_words()
[('Jersei','N'),('atinge','V'),('m\xe9dia','N'),...]
>>>nltk.corpus.conll2002.tagged_words()
[('Sao','NC'),('Paulo','VMI'),('(','Fpa'),...]
>>>nltk.corpus.cess_cat.tagged_words()
[('El','da0ms0'),('Tribunal_Suprem','np0000o'),...]
Figure5.1:POS-TaggedDatafromFourIndianLanguages:Bangla,Hindi,Marathi,andTelugu
Ifthecorpusisalsosegmentedintosentences,itwillhaveatagged_sents()methodthatdividesupthetaggedwordsintosentencesratherthanpresentingthemasonebiglist.Thiswillbeusefulwhenwecometodevelopingautomatictaggers,astheyaretrainedandtestedonlistsofsentences,notwords.
Tag
Meaning
Examples
ADJ
adjective
new,good,high,special,big,local
ADV
adverb
really,already,still,early,now
CNJ
conjunction
and,or,but,if,while,although
DET
determiner
the,a,some,most,every,no
EX
existential
there,there's
FW
foreignword
dolce,ersatz,esprit,quo,maitre
MOD
modalverb
will,can,would,may,must,should
N
noun
year,home,costs,time,education
NP
propernoun
Alison,Africa,April,Washington
NUM
number
twenty-four,fourth,1991,14:24
PRO
pronoun
he,their,her,its,my,I,us
P
preposition
on,of,at,with,by,into,under
TO
thewordto
to
UH
interjection
ah,bang,ha,whee,hmpf,oops
V
verb
is,has,get,do,make,see,run
VD
pasttense
said,took,told,made,asked
VG
presentparticiple
making,going,playing,working
VN
pastparticiple
given,taken,begun,sung
WH
whdeterminer
who,which,when,what,where,howTable5.1:
SimplifiedPart-of-SpeechTagset
Let'sseewhichofthesetagsarethemostcommoninthenewscategoryoftheBrowncorpus:
>>>fromnltk.corpusimportbrown
>>>brown_news_tagged=brown.tagged_words(categories='news',simplify_tags=True)
>>>tag_fd=nltk.FreqDist(tagfor(word,tag)inbrown_news_tagged)
>>>tag_fd.keys()
['N','P','DET','NP','V','ADJ',',','.','CNJ','PRO','ADV','VD',...]
Note
WecanusethesetagstodopowerfulsearchesusingagraphicalPOS-concordancetoolnltk.app.concordance().UseittosearchforanycombinationofwordsandPOStags,e.g.NNNN,hit/VD,hit/VN,ortheADJman.
Nouns名词
Word
Afteradeterminer
Subjectoftheverb
woman
thewomanwhoIsawyesterday...
thewomansatdown
Scotland
theScotlandIrememberasachild...
Scotlandhasfivemillionpeople
book
thebookIboughtyesterday...
thisbookrecountsthecolonizationofAustralia
intelligence
theintelligencedisplayedbythechild...
Mary'sintelligenceimpressedherteachersTable5.2:
SyntacticPatternsinvolvingsomeNouns
ThesimplifiednountagsareNforcommonnounslikebook,andNPforpropernounslikeScotland.
Let'sinspectsometaggedtexttoseewhatpartsofspeechoccurbeforeanoun,withthemostfrequentonesfirst.Tobeginwith,weconstructalistofbigramswhosemembersarethemselvesword-tagpairssuchas(('The','DET'),('Fulton','NP'))and(('Fulton','NP'),('County','N')).ThenweconstructaFreqDistfromthetagpartsofthebigrams.
>>>word_tag_pairs=nltk.bigrams(brown_news_tagged)
>>>list(nltk.FreqDist(a[1]for(a,b)inword_tag_pairsifb[1]=='N'))
['DET','ADJ','N','P','NP','NUM','V','PRO','CNJ','.',',','VG','VN',...]
(a,b)也就是(('The','DET'),('Fulton','NP')),如果b[1]==’N’,则给出前面这个词的词性a[1]
Thisconfirmsourassertionthatnounsoccurafterdeterminersandadjectives,includingnumeraladjectives(taggedasNUM).
Verbs动词
Simple
Withmodifiersandadjuncts(italicized)
fall
Romefell
Dotcomstockssuddenlyfelllikeastone
eat
Miceeatcheese
JohnatethepizzawithgustoTable5.3:
SyntacticPatternsinvolvingsomeVerbs
WhatarethemostcommonverbsinnewstextLet'ssortalltheverbsbyfrequency:
>>>wsj=nltk.corpus.treebank.tagged_words(simplify_tags=True)
>>>word_tag_fd=nltk.FreqDist(wsj)
>>>[word+"/"+tagfor(word,tag)inword_tag_fdiftag.startswith('V')]
['is/V','said/VD','was/VD','are/V','be/V','has/V','have/V','says/V',
'were/VD','had/VD','been/VN',"'s/V",'do/V','say/V','make/V','did/VD',
'rose/VD','does/V','expected/VN','buy/V','take/V','get/V','sell/V',
'help/V','added/VD','including/VG','according/VG','made/VN','pay/V',...]
Notethattheitemsbeingcountedinthefrequencydistributionareword-tagpairs.Sincewordsandtagsarepaired,wecantreatthewordasaconditionandthetagasanevent,andinitializeaconditionalfrequencydistributionwithalistofcondition-eventpairs.Thisletsusseeafrequency-orderedlistoftagsgivenaword:
>>>cfd1=nltk.ConditionalFreqDist(wsj)
>>>cfd1['yield'].keys()
['V','N']
>>>cfd1['cut'].keys()
['V','VD','N','VN']
Wecanreversetheorderofthepairs,sothatthetagsaretheconditions,andthewordsaretheevents(词作为条件,标签作为事件).Nowwecanseelikelywordsforagiventag:
>>>cfd2=nltk.ConditionalFreqDist((tag,word)for(word,tag)inwsj)
>>>cfd2['VN'].keys()
['been','expected','made','compared','based','priced','used','sold',
'named','designed','held','fined','taken','paid','traded','said',...]
ToclarifythedistinctionbetweenVD(pasttense)andVN(pastparticiple),let'sfindwordswhichcanbebothVDandVN,andseesomesurroundingtext:
>>>[wforwincfd1.conditions()if'VD'incfd1[w]and'VN'incfd1[w]]
['Asked','accelerated','accepted','accused','acquired','added','adopted',...]
>>>idx1=wsj.index(('kicked','VD'))
>>>wsj[idx1-4:idx1+1]
[('While','P'),('program','N'),('trades','N'),('swiftly','ADV'),
('kicked','VD')]
>>>idx2=wsj.index(('kicked','VN'))
>>>wsj[idx2-4:idx2+1]
[('head','N'),('of','P'),('state','N'),('has','V'),('kicked','VN')]
Inthiscase,weseethatthepastparticipleofkickedisprecededbyaformoftheauxiliaryverbhave.Isthisgenerallytrue
AdjectivesandAdverbs形容词和副词
Twootherimportantwordclassesareadjectivesandadverbs.Adjectivesdescribenouns,andcanbeusedasmodifiers(e.g.largeinthelargepizza),orinpredicates(e.g.thepizzaislarge).Englishadjectivescanhaveinternalstructure(e.g.fall+inginthefallingstocks).Adverbsmodifyverbstospecifythetime,manner,placeordirectionoftheeventdescribedbytheverb(e.g.quicklyinthestocksfellquickly).Adverbsmayalsomodifyadjectives(e.g.reallyinMary'steacherwasreallynice).
Englishhasseveralcategoriesofclosedclasswordsinadditiontoprepositions,suchasarticles(alsooftencalleddeterminers)(e.g.,the,a),modals(e.g.,should,may),andpersonalpronouns(e.g.,she,they).Eachdictionaryandgrammarclassifiesthesewordsdifferently.
UnsimplifiedTags未简化的标签
deffindtags(tag_prefix,tagged_text):
cfd=nltk.ConditionalFreqDist((tag,word)for(word,tag)intagged_text
iftag.startswith(tag_prefix))
returndict((tag,cfd[tag].keys()[:5])fortagincfd.conditions())
>>>tagdict=findtags('NN',nltk.corpus.brown.tagged_words(categories='news'))
>>>fortaginsorted(tagdict):
...printtag,tagdict[tag]
...
NN['year','time','state','week','man']
NN$["year's","world's","state's","nation's","company's"]
NN$-HL["Golf's","Navy's"]
NN$-TL["President's","University's","League's","Gallery's","Army's"]
NN-HL['cut','Salary','condition','Question','business']
NN-NC['eva','ova','aya']
NN-TL['President','House','State','University','City']
NN-TL-HL['Fort','City','Commissioner','Grove','House']
NNS['years','members','people','sales','men']
NNS$["children's","women's","men's","janitors'","taxpayers'"]
NNS$-HL["Dealers'","Idols'"]
NNS$-TL["Women's","States'","Giants'","Officers'","Bombers'"]
NNS-HL['years','idols','Creations','thanks','centers']
NNS-TL['States','Nations','Masters','Rules','Communists']
NNS-TL-HL['Nations']
Whenwecometoconstructingpart-of-speechtaggerslaterinthischapter,wewillusetheunsimplifiedtags.
ExploringTaggedCorpora探索标注的语料库
Let'sbrieflyreturntothekindsofexplorationofcorporawesawinpreviouschapters,thistimeexploitingPOStags.
Supposewe'restudyingthewordoftenandwanttoseehowitisusedintext.Wecouldasktoseethewordsthatfollowoften
>>>brown_learned_text=brown.words(categories='learned')
>>>sorted(set(bfor(a,b)innltk.ibigrams(brown_learned_text)ifa=='often'))
[',','.','accomplished','analytically','appear','apt','associated','assuming',
'became','become','been','began','call','called','carefully','chose',...]
However,it'sprobablymoreinstructiveusethetagged_words()methodtolookatthepart-of-speechtagofthefollowingwords:
>>>brown_lrnd_tagged=brown.tagged_words(categories='learned',simplify_tags=True)
>>>tags=[b[1]for(a,b)innltk.ibigrams(brown_lrnd_tagged)ifa[0]=='often']
>>>fd=nltk.FreqDist(tags)
>>>fd.tabulate()
VNVVDDETADJADVPCNJ,TOVGWHVBZ.
1512855443311111
Noticethatthemosthigh-frequencypartsofspeechfollowingoftenareverbs.Nounsneverappearinthisposition(inthisparticularcorpus).
Next,let'slookatsomelargercontext,andfindwordsinvolvingparticularsequencesoftagsandwords(inthiscase"
fromnltk.corpusimportbrown
defprocess(sentence):
for(w1,t1),(w2,t2),(w3,t3)innltk.trigrams(sentence):
if(t1.startswith('V')andt2=='TO'andt3.startswith('V')):
printw1,w2,w3
>>>fortagged_sentinbrown.tagged_sents():
...process(tagged_sent)
combinedtoachieve
continuetoplace
servetoprotect
wantedtowait
allowedtoplace
expectedtobecome
Finally,let'slookforwordsthatarehighlyambiguousastotheirpartofspeechtag.Understandingwhysuchwordsaretaggedastheyareineachcontextcanhelpusclarifythedistinctionsbetweenthetags.
>>>data=nltk.ConditionalFreqDist((word.lower(),tag)
...for(word,tag)inbrown_news_tagged)
>>>forwordindata.conditions():
...iflen(data[word])>3:
...tags=data[word].keys()
...printword,''.join(tags)
bestADJADVNPV
betterADJADVVDET
closeADVADJVN
cutVNVNVD
evenADVDETADJV
grantNPNV-
hitVVDVNN
layADJVNPVD
leftVDADJNVN
likeCNJVADJP-
nearPADVADJDET
openADJVNADV
pastNADJDETP
presentADJADVVN
readVVNVDNP
rightADJNDETADV
secondNUMADVDETN
setVNVVDN-
thatCNJVWHDET
CC-CoordinatingconjunctionCD-CardinalnumberDT-DeterminerEX-ExistentialthereFW-ForeignwordIN-PrepositionorsubordinatingconjunctionJJ-AdjectiveJJR-Adjective,comparativeJJS-Adjective,superlativeLS-ListitemmarkerMD-ModalNN-Noun,singularormassNNS-Noun,pluralNNP-Propernoun,singularNNPS-Propernoun,pluralPDT-PredeterminerPOS-PossessiveendingPRP-PersonalpronounPRP$-PossessivepronounRB-AdverbRBR-Adverb,comparativeRBS-Adverb,superlativeRP-ParticleSYM-SymbolTO-toUH-InterjectionVB-Verb,baseformVBD-Verb,pasttenseVBG-Verb,gerundorpresentparticipleVBN-Verb,pastparticipleVBP-Verb,non-3rdpersonsingularpresentVBZ-Verb,3rdpersonsingularpresentWDT-Wh-determinerWP-Wh-pronounWP$-Possessivewh-pronounWRB-Wh-adverb
CC-CoordinatingconjunctionCD-CardinalnumberDT-DeterminerEX-ExistentialthereFW-ForeignwordIN-PrepositionorsubordinatingconjunctionJJ-AdjectiveJJR-Adjective,comparativeJJS-Adjective,superlativeLS-ListitemmarkerMD-ModalNN-Noun,singularormassNNS-Noun,pluralNNP-Propernoun,singularNNPS-Propernoun,pluralPDT-PredeterminerPOS-PossessiveendingPRP-PersonalpronounPRP$-PossessivepronounRB-AdverbRBR-Adverb,comparativeRBS-Adverb,superlativeRP-ParticleSYM-SymbolTO-toUH-InterjectionVB-Verb,baseformVBD-Verb,pasttenseVBG-Verb,gerundorpresentparticipleVBN-Verb,pastparticipleVBP-Verb,non-3rdpersonsingularpresentVBZ-Verb,3rdpersonsingularpresentWDT-Wh-determinerWP-Wh-pronounWP$-Possessivewh-pronounWRBWh-adverbhoweverwheneverwherewhy
安装pip命令之后:
sudopipinstall-Upyyamlnltk
importnltknltk.download()等待ing
目前访问不了,故使用GreenVPN
nltk使用
1.空格进行英文分词.split(python自带)
>>>entities=nltk.chunk.ne_chunk(tagged)>>>entitiesTree('S',[(u'\u6211\u4eec\u90fdLike','IN'),(u'the','DT'),(u'book','NN')])>>>---------------------------------------------------------------------------------------------------------------------------------------------------------
4.转换为小写(Python自带)
这篇,初步介绍了如何开始使用nltk的语料和他的一些常用方法.有点python基础的可以直接看了.之所以放在这里,还是因为,只有安装好了才可以进行到这一步.
这一篇也挺浅显易懂的.
nltk怎么样使用中文这是个大问题。这么个工具目前只能比较好的处理英文和其他的一些拉丁语系,谁让别人的单词与单词之间有个空格隔开呢!中文汉字一个挨一个的,nltk在分词这一关就过不去了,分词没法分,剩下的就都做不了。唯一能做的,就是对网上现有的中文语料进行处理,这些语料都分好了词,可以使用nltk进行类似与英文的处理。
python处理中文首先需要设置一下文本的编码,文件的首行加上:#codingutf-8这个是给python解释器识别的,然后文件保存的时候,还需要保存为utf-8的编码。
这些编码设置完了,ntlk还是处理不了中文。
nltk处理中文的第一步障碍就是中文资料不是分好词的,词语与词语之间没有空格。要使用nltk对中文进行处理,首先的第一步就是中文分词(台湾叫中文断词)。
当然中文分词,不应该成为使用nltk的障碍,或许很多人认为,既然用nltk,那么nltk就应该支持中文。但是我们得认清现实,现实就是nltk就是不支持处理中文,因此,这个给国内很多自然语言处理的研究人员有了研究的空间了,nltk既然没做中文分词,那么中国人就应该自己做了这个。一个口碑比较好的中文分词工具就是ICTCLAS中文分词。
当然,我个人觉得中国人自己开发的纯python实现的结巴分词也不错。
总的来说,nltk不提供中文分词,不应该纠结于此,并止步不前,我们完全可以使用其他的中文分词工具,将需要处理的资料分好词,然后再使用nltk进行处理,因此,这里就不多说中文分词的那点事了。如果你因为中文分词而分心,并转向到中文分词的研究之中,那么你就掉入了另外一个深坑之中。牢记本文的主题是nltk。当然需要多啰嗦一点的就是,nltk的默认词性标注集使用的是PennTreebank的词性标注集,因此,你选用中文分词模块的时候,最好能够使用和penn词性标注集差不多的中文分词工具,当然,不一样也没事。
啥叫高级啊?就是基础掌握了之后,开始运用实际工作了,就叫高级。比如什么统计推荐,评分,机器翻译,文本分类,舆情监控等等都是高级应用。
下面是些入门资料。
何谓精通?精通就是熟练的表达你的想法。
何谓精通一个工具?就是你想做什么,你就能用这个工具顺利的完成。doeverythingyouwantwithnltk.
至于如何精通,建议多看英文资料和多动手操练。nltk官方文档,一些参与nltk的大学研究机构,北大,清华的语言研究以及国际语言研究机构acl所发的论文等等。
假设你目前真的熟练的掌握了nltk的各种玩法了,那么,你精通的标志就是改造nltk,使它功能更强,更优,更快,更方便。
比如:
6.1集成结巴分词到nltk的分词器之中
6.2在国内多弄几个地方,放置nltk_data数据包,方便大家下载
6.3给nltk提供语料
等等,剩下的由你来补充。
阅读目录
2016年11月6日19:28:43
NLTK:由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公开数据集、模型上提供了全面、易用的接口,涵盖了分词、词性标注(Part-Of-Speechtag,POS-tag)、命名实体识别(NamedEntityRecognition,NER)、句法分析(SyntacticParse)等各项NLP领域的功能。
StanfordNLP:由斯坦福大学的NLP小组开源的Java实现的NLP工具包,同样对NLP领域的各个问题提供了解决办法。斯坦福大学的NLP小组是世界知名的研究小组,能将NLTK和StanfordNLP这两个工具包结合起来使用,那对于自然语言开发者是再好不过的!在2004年SteveBird在NLTK中加上了对StanfordNLP工具包的支持,通过调用外部的jar文件来使用StanfordNLP工具包的功能。本分析显得非常方便好用。
本文在主要介绍NLTK中提供StanfordNLP中的以下几个功能:
本文以Python3.5.2和javaversion"1.8.0_111"版本进行配置,具体安装需要注意以下几点:
以上文件下载后,Jar如果是1.8的版本可以不用下载,另外两个压缩包下载到本地,解压后拷贝文件夹到你的python安装主路径下,然后cmd进入NLTK下通过pythonsetup.pyinstall即可。后面操作讲路径简单修改即可。(如果不能正常分词等操作,查看python是否是3.2以上版本,java是否是8以后版本,jar环境变量是否配置正确)
StanfordNLTK目录结构如下:(从各个压缩文件已经提取好了,如果读者感兴趣,下面有各个功能的源码文件)
压缩包下载和源码分析:
执行结果:
程序解读:StanfordSegmenter的初始化参数说明:
StanfordNERTagger英文命名实体识别
运行结果:
StanfordNERTagger中文命名实体识别
StanfordPOSTagger英文词性标注
StanfordPOSTagger中文词性标注
StanfordParser英文语法分析
StanfordParser中文句法分析
StanfordDependencyParser英文依存句法分析
StanfordDependencyParser中文依存句法分析
什么是词干提取?
一个面向英语的词干提取器,例如,要识别字符串“cats”、“catlike”和“catty”是基于词根“cat”;“stemmer”、“stemming”和“stemmed”是基于词根“stem”。一根词干提取算法可以简化词“fishing”、“fished”、“fish”和“fisher”为同一个词根“fish”。技术方案的选择
Python和R是数据分析的两种主要语言;相对于R,Python更适合有大量编程背景的数据分析初学者,尤其是已经掌握Python语言的程序员。所以我们选择了Python和NLTK库(NatualLanguageTookit)作为文本处理的基础框架。此外,我们还需要一个数据展示工具;对于一个数据分析师来说,数据库的冗繁安装、连接、建表等操作实在是不适合进行快速的数据分析,所以我们使用Pandas作为结构化数据和分析工具。环境搭建
我们使用的是MacOSX,已预装Python2.7.
安装NLTK
安装Pandas
对于数据分析来说,最重要的是分析结果,iPythonnotebook是必备的一款利器,它的作用在于可以保存代码的执行结果,例如数据表格,下一次打开时无需重新运行即可查看。
安装iPythonnotebook
文本处理
数据表创建
使用Pandas创建数据表我们使用得到的样本数据,建立DataFrame——Pandas中一个支持行、列的2D数据结构。
显示结果
NLTK分词器介绍
接下来,对准备好的数据表进行处理,添加词干将要写入的列,以及统计列,预设默认值为1:
读取数据表中的Words列,使用波特词干提取器取得词干:
Good!到这一步,我们已经基本上实现了文本处理,结果显示如下:
分组统计
在Pandas中进行分组统计,将统计表格保存到一个新的DataFrame结构uniqueWords中:
注意到了吗?依然还有一个petinsu未能成功处理。
拼写检查
对于用户拼写错误的词语,我们首先想到的是拼写检查,针对Python我们可以使用enchant:
使用enchant进行拼写错误检查,得到推荐词:
但是,结果依然不是我们预期的“insur”。能不能换种思路呢?算法特殊性
用户输入非常重要的特殊性来自于行业和使用场景。采取通用的英语大词典来进行拼写检查,无疑是行不通的,并且某些词语恰恰是拼写正确,但本来却应该是另一个词。但是,我们如何把这些背景信息和数据分析关联起来呢?
经过一番思考,我认为最重要的参考库恰恰就在已有的数据分析结果中,我们回来看看:
已有的5个“petinsur”,其实就已经给我们提供了一份数据参考,我们已经可以对这份数据进行聚类,进一步除噪。
相似度计算
对已有的结果进行相似度计算,将满足最小偏差的数据归类到相似集中:
查看结果,已经匹配成功!
最后一步,重新对数据结果进行分组统计:
到此,我们已经完成了初步的文本处理。
本节介绍我的分类实战过程。
个人实战过程到此结束,有问题的地方户在后期的学习中慢慢改进。
Bases:object
Aprocessinginterfaceforremovingmorphologicalaffixesfromwords.Thisprocessisknownasstemming.
Stripaffixesfromthetokenandreturnthestem.
ISRIArabicStemmer
Thealgorithmforthisstemmerisdescribedin:
Taghva,K.,Elkoury,R.,andCoombs,J.2005.ArabicStemmingwithoutarootdictionary.InformationScienceResearchInstitute.UniversityofNevada,LasVegas,USA.
TheInformationScienceResearchInstitute’s(ISRI)ArabicstemmersharesmanyfeatureswiththeKhojastemmer.However,themaindifferenceisthatISRIstemmerdoesnotuserootdictionary.Also,ifarootisnotfound,ISRIstemmerreturnednormalizedform,ratherthanreturningtheoriginalunmodifiedword.
Additionaladjustmentsweremadetoimprovethealgorithm:
1-Adding60stopwords.2-Addingthepattern()toISRIpatternset.3-Thestep2intheoriginalalgorithmwasnormalizingallhamza.Thisstepisdiscardedbecauseitincreasesthewordambiguitiesandchangestheoriginalroot.
ISRIArabicstemmerbasedonalgorithm:ArabicStemmingwithoutarootdictionary.InformationScienceResearchInstitute.UniversityofNevada,LasVegas,USA.
AfewminormodificationshavebeenmadetoISRIbasicalgorithm.Seethesourcecodeofthismoduleformoreinformation.
isri.stem(token)returnsArabicrootforthegiventoken.
TheISRIStemmerrequiresthatalltokenshaveUnicodestringtypes.IfyouusePythonIDLEonArabicWindowsyouhavetodecodetextfirstusingArabic‘1256’coding.
endingstep(wordoflengthfive)
endingstep(wordoflengthsix)
normalization:num=1normalizediacriticsnum=2normalizeinitialhamzanum=3both1&2
normalizeshortprefix
removelengththreeandlengthtwoprefixesinthisorder
processlengthfourpatternsandextractlengththreeroots
processlengthfivepatternsandextractlengththreeroots
processlengthfivepatternsandextractlengthfourroots
processlengthsixpatternsandextractlengththreeroots
processlengthsixpatternsandextractlengthfourroots
StemmingawordtokenusingtheISRIstemmer.
normalizeshortsufix
removelengththreeandlengthtwosuffixesinthisorder
removeconnective‘’ifitprecedesawordbeginningwith‘’
AwordstemmerbasedontheLancasterstemmingalgorithm.Paice,ChrisD.“AnotherStemmer.”ACMSIGIRForum24.3(1990):56-61.
LancasterStemmer
StemawordusingtheLancasterstemmer.
PorterStemmer
ThisisthePorterstemmingalgorithm.Itfollowsthealgorithmpresentedin
Porter,M.“Analgorithmforsuffixstripping.”Program14.3(1980):130-137.
withsomeoptionaldeviationsthatcanbeturnedonoroffwiththemodeargumenttotheconstructor.
MartinPorter,thealgorithm’sinventor,maintainsawebpageaboutthealgorithmat
whichincludesanotherPythonimplementationandotherimplementationsinmanylanguages.
AwordstemmerbasedonthePorterstemmingalgorithm.
MartinPorterhasendorsedseveralmodificationstothePorteralgorithmsincewritinghisoriginalpaper,andthoseextensionsareincludedintheimplementationsonhiswebsite.Additionally,othershaveproposedfurtherimprovementstothealgorithm,includingNLTKcontributors.Therearethusthreemodesthatcanbeselectedbypassingtheappropriateconstanttotheclassconstructor’smodeattribute:
PorterStemmer.ORIGINAL_ALGORITHM-Implementationthatisfaithfultotheoriginalpaper.
NotethatMartinPorterhasdeprecatedthisversionofthealgorithm.MartindistributesimplementationsofthePorterStemmerinmanylanguages,hostedat:
andalloftheseimplementationsincludehisextensions.Hestronglyrecommendsagainstusingtheoriginal,publishedversionofthealgorithm;onlyusethismodeifyouclearlyunderstandwhyyouarechoosingtodoso.
PorterStemmer.MARTIN_EXTENSIONS-Implementationthatonlyusesthemodificationstothe
PorterStemmer.NLTK_EXTENSIONS(default)-Implementationthatincludesfurtherimprovementsdevisedby
Forthebeststemming,youshouldusethedefaultNLTK_EXTENSIONSversion.However,ifyouneedtogetthesameresultsaseithertheoriginalalgorithmoroneofMartinPorter’shostedversionsforcompabilitywithanexistingimplementationordataset,youcanuseoneoftheothermodesinstead.
AdemonstrationoftheporterstemmeronasamplefromthePennTreebankcorpus.
Astemmerthatusesregularexpressionstoidentifymorphologicalaffixes.Anysubstringsthatmatchtheregularexpressionswillberemoved.
AstemmerforPortuguese.
Snowballstemmers
ThismoduleprovidesaportoftheSnowballstemmersdevelopedbyMartinPorter.
Thereisalsoademofunction:snowball.demo().
Bases:nltk.stem.snowball._ScandinavianStemmer
TheDanishSnowballstemmer.
StemaDanishwordandreturnthestemmedform.
Bases:nltk.stem.snowball._StandardStemmer
TheDutchSnowballstemmer.
StemaDutchwordandreturnthestemmedform.
TheEnglishSnowballstemmer.
StemanEnglishwordandreturnthestemmedform.
TheFinnishSnowballstemmer.
StemaFinnishwordandreturnthestemmedform.
TheFrenchSnowballstemmer.
StemaFrenchwordandreturnthestemmedform.
TheGermanSnowballstemmer.
StemaGermanwordandreturnthestemmedform.
Bases:nltk.stem.snowball._LanguageSpecificStemmer
TheHungarianSnowballstemmer.
StemanHungarianwordandreturnthestemmedform.
TheItalianSnowballstemmer.
StemanItalianwordandreturnthestemmedform.
TheNorwegianSnowballstemmer.
StemaNorwegianwordandreturnthestemmedform.
AwordstemmerbasedontheoriginalPorterstemmingalgorithm.
AfewminormodificationshavebeenmadetoPorter’sbasicalgorithm.Seethesourcecodeofthemodulenltk.stem.porterformoreinformation.
ThePortugueseSnowballstemmer.
StemaPortuguesewordandreturnthestemmedform.
TheRomanianSnowballstemmer.
StemaRomanianwordandreturnthestemmedform.
TheRussianSnowballstemmer.
StemaRussianwordandreturnthestemmedform.
SnowballStemmer
Thefollowinglanguagesaresupported:Danish,Dutch,English,Finnish,French,German,Hungarian,Italian,Norwegian,Portuguese,Romanian,Russian,SpanishandSwedish.
ThealgorithmforEnglishisdocumentedhere:
Thestemmerisinvokedasshownbelow:
>>>fromnltk.stemimportSnowballStemmer>>>print("".join(SnowballStemmer.languages))#Seewhichlanguagesaresupporteddanishdutchenglishfinnishfrenchgermanhungarianitaliannorwegianporterportugueseromanianrussianspanishswedish>>>stemmer=SnowballStemmer("german")#Choosealanguage>>>stemmer.stem("Autobahnen")#Stemaword'autobahn'Invokingthestemmersthatwayisusefulifyoudonotknowthelanguagetobestemmedatruntime.Alternatively,ifyoualreadyknowthelanguage,thenyoucaninvokethelanguagespecificstemmerdirectly:
>>>fromnltk.stem.snowballimportGermanStemmer>>>stemmer=GermanStemmer()>>>stemmer.stem("Autobahnen")'autobahn'Parameters:Raises:ValueError–Ifthereisnostemmerforthespecifiedlanguage,aValueErrorisraised.
TheSpanishSnowballstemmer.
StemaSpanishwordandreturnthestemmedform.
TheSwedishSnowballstemmer.
StemaSwedishwordandreturnthestemmedform.
ThisfunctionprovidesademonstrationoftheSnowballstemmers.
Afterinvokingthisfunctionandspecifyingalanguage,itstemsanexcerptoftheUniversalDeclarationofHumanRights(whichisapartoftheNLTKcorpuscollection)andthenprintsouttheoriginalandthestemmedtext.
Replacestheoldsuffixoftheoriginalstringbyanewsuffix
WordNetLemmatizer
LemmatizeusingWordNet’sbuilt-inmorphyfunction.ReturnstheinputwordunchangedifitcannotbefoundinWordNet.
NLTKStemmers
Interfacesusedtoremovemorphologicalaffixesfromwords,leavingonlythewordstem.Stemmingalgorithmsaimtoremovethoseaffixesrequiredforeg.grammaticalrole,tense,derivationalmorphologyleavingonlythestemoftheword.Thisisadifficultproblemduetoirregularwords(eg.commonverbsinEnglish),complicatedmorphologicalrules,andpart-of-speechandsenseambiguities(eg.ceil-isnotthestemofceiling).