python自然语言处理工具NLTK各个包的意思和作用总结

【转】http://www.myexception.cn/perl-python/464414.html

 

 

【原】Python NLP实战之一:环境准备
最近正在学习Python,看了几本关于Python入门的书和用Python进行自然语言处理的书,如《Python编程实践》、《Python基础教程》(第2版)、《Python自然语言处理》(影印版)。因为以前是学Java的,有着良好的面向对象的思维方式,所以刚开始看Python的语法,觉得Pyhon太随意了,很别扭,有不正规之嫌。而且,Python自己也正在向面向对象(OO)靠拢。但是,后来看到Python有强大的类库,尤其在自然语言处理方面有着强大的NLTK支持,我逐渐改变了对它的看法。不得不承认,Python非常简洁和清晰,很容易上手,对于有编程经验的人来说,可以快速编写程序来实现某个应用。下面是本人学习中的一些心得,与大家分享。

Python NLP实战之一:环境准备

要下载和安装的软件和资源有:

  • Python
  • PyYAML
  • NLTK
  • NLTK-Data
  • NumPy
  • Matplotlib


(一)下载地址和版本:

  • Python:http://www.python.org/getit/releases/2.7.2/ 版本:Python 2.7.2 (注:现在是2.7.3。Python已经发布3.3版了,之所以下载2.7,是因为2.x比较稳定,兼容的第三方软件多。Python官网提示:如果你不知道用哪个版本的话,就从2.7开始吧!)
  • PyYAML:http://pypi.python.org/pypi/PyYAML/ 版本:PyYAML 3.10 功能:YAML的解析工具
  • NLTK: http://www.nltk.org 版本:nltk-2.0.1 功能:自然语言工具包
  • NumPy: http://pypi.python.org/pypi/numpy 版本:numpy 1.6.1 功能:支持多维数组和线性代数
  • Matplotlib: http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/ 版本:matplotlib-1.1.0 功能:用于数据可视化的二维图库

安装都很简单,我是在Window下安装的。

(二)运行Python IDLE
Python安装完成后,运行Python集成开发环境IDLE:开始->所有程序->Python 2.7 ->IDLE (Python GUI),打开一个新的窗口,显示如下信息,表明安装成功。

[java]  view plain  copy
  1. Python 2.7.2 (default, Jun 12 201115:08:59) [MSC v.1500 32 bit (Intel)] on win32  
  2. Type "copyright""credits" or "license()" for more information.  
  3. >>>  


(三)下载NLTK数据包
接下来,导入NLTK工具包,然后,下载NLTK数据源。

[java]  view plain  copy
  1. >>> import nltk  
  2. >>> nltk.download()  



注意:在导入MLTK工具包时,如果显示如下信息,表明没有安装PyYAML。

[java]  view plain  copy
  1. >>> import nltk  
  2. Traceback (most recent call last):  
  3.   File "<pyshell#0>", line 1, in <module>  
  4.     import nltk  
  5.   File "C:\Python27\lib\site-packages\nltk\__init__.py", line 107, in <module>  
  6.     from yamltags import *  
  7.   File "C:\Python27\lib\site-packages\nltk\yamltags.py", line 10, in <module>  
  8.     import yaml  
  9. ImportError: No module named yaml  



按照(一)所列的地址下载、安装完PyYAML后,再打开Python IDLE,导入NLTK,执行nltk.download(),我的界面出现的是文字提示,书上和网上有同学说是图形界面,两者都可以吧。

[java]  view plain  copy
  1. Python 2.7.2 (default, Jun 12 201115:08:59) [MSC v.1500 32 bit (Intel)] on win32  
  2. Type "copyright""credits" or "license()" for more information.  
  3. >>> import nltk  
  4. >>> nltk.download()  
  5. NLTK Downloader  
  6. ---------------------------------------  
  7.     d) Download   l) List    u) Update   c) Config   h) Help   q) Quit  
  8. ---------------------------------------  
  9. Downloader>  


选择d) Download,敲入d,再敲入l,然后按提示敲几次回车,显示的是将要下载的各种不同的数据包。

[java]  view plain  copy
  1. Downloader> d  
  2. Download which package (l=list; x=cancel)?  
  3.   Identifier> l  
  4. Packages:  
  5.   [ ] maxent_ne_chunker... ACE Named Entity Chunker (Maximum entropy)  
  6.   [ ] abc................. Australian Broadcasting Commission 2006  
  7.   [ ] alpino.............. Alpino Dutch Treebank  
  8.   [ ] biocreative_ppi..... BioCreAtIvE (Critical Assessment of Information  
  9.                            Extraction Systems in Biology)  
  10.   [ ] brown_tei........... Brown Corpus (TEI XML Version)  
  11.   [ ] cess_esp............ CESS-ESP Treebank  
  12.   [ ] chat80.............. Chat-80 Data Files  
  13.   [ ] brown............... Brown Corpus  
  14.   [ ] cmudict............. The Carnegie Mellon Pronouncing Dictionary (0.6)  
  15.   [ ] city_database....... City Database  
  16.   [ ] cess_cat............ CESS-CAT Treebank  
  17.   [ ] comtrans............ ComTrans Corpus Sample  
  18.   [ ] conll2002........... CONLL 2002 Named Entity Recognition Corpus  
  19.   [ ] conll2007........... Dependency Treebanks from CoNLL 2007 (Catalan  
  20.                            and Basque Subset)  
  21.   [ ] europarl_raw........ Sample European Parliament Proceedings Parallel  
  22.                            Corpus  
  23.   [ ] dependency_treebank. Dependency Parsed Treebank  
  24.   [ ] conll2000........... CONLL 2000 Chunking Corpus  
  25. Hit Enter to continue:   
  26.   [ ] floresta............ Portuguese Treebank  
  27.   [ ] names............... Names Corpus, Version 1.3 (1994-03-29)  
  28.   [ ] gazetteers.......... Gazeteer Lists  
  29.   [ ] genesis............. Genesis Corpus  
  30.   [ ] gutenberg........... Project Gutenberg Selections  
  31.   [ ] inaugural........... C-Span Inaugural Address Corpus  
  32.   [ ] jeita............... JEITA Public Morphologically Tagged Corpus (in  
  33.                            ChaSen format)  
  34.   [ ] movie_reviews....... Sentiment Polarity Dataset Version 2.0  
  35.   [ ] ieer................ NIST IE-ER DATA SAMPLE  
  36.   [ ] nombank.1.0......... NomBank Corpus 1.0  
  37.   [ ] indian.............. Indian Language POS-Tagged Corpus  
  38.   [ ] paradigms........... Paradigm Corpus  
  39.   [ ] kimmo............... PC-KIMMO Data Files  
  40.   [ ] knbc................ KNB Corpus (Annotated blog corpus)  
  41.   [ ] langid.............. Language Id Corpus  
  42.   [ ] mac_morpho.......... MAC-MORPHO: Brazilian Portuguese news text with  
  43.                            part-of-speech tags  
  44.   [ ] machado............. Machado de Assis -- Obra Completa  
  45.   [ ] pe08................ Cross-Framework and Cross-Domain Parser  
  46.                            Evaluation Shared Task  
  47. Hit Enter to continue:   
  48.   [ ] pl196x.............. Polish language of the XX century sixties  
  49.   [ ] pil................. The Patient Information Leaflet (PIL) Corpus  
  50.   [ ] nps_chat............ NPS Chat  
  51.   [ ] reuters............. The Reuters-21578 benchmark corpus, ApteMod  
  52.                            version  
  53.   [ ] qc.................. Experimental Data for Question Classification  
  54.   [ ] rte................. PASCAL RTE Challenges 12, and 3  
  55.   [ ] ppattach............ Prepositional Phrase Attachment Corpus  
  56.   [ ] propbank............ Proposition Bank Corpus 1.0  
  57.   [ ] problem_reports..... Problem Report Corpus  
  58.   [ ] sinica_treebank..... Sinica Treebank Corpus Sample  
  59.   [ ] verbnet............. VerbNet Lexicon, Version 2.1  
  60.   [ ] state_union......... C-Span State of the Union Address Corpus  
  61.   [ ] semcor.............. SemCor 3.0  
  62.   [ ] senseval............ SENSEVAL 2 Corpus: Sense Tagged Text  
  63.   [ ] smultron............ SMULTRON Corpus Sample  
  64.   [ ] shakespeare......... Shakespeare XML Corpus Sample  
  65.   [ ] stopwords........... Stopwords Corpus  
  66.   [ ] swadesh............. Swadesh Wordlists  
  67.   [ ] switchboard......... Switchboard Corpus Sample  
  68.   [ ] toolbox............. Toolbox Sample Files  
  69. Hit Enter to continue:   
  70.   [ ] unicode_samples..... Unicode Samples  
  71.   [ ] webtext............. Web Text Corpus  
  72.   [ ] timit............... TIMIT Corpus Sample  
  73.   [ ] ycoe................ York-Toronto-Helsinki Parsed Corpus of Old  
  74.                            English Prose  
  75.   [ ] treebank............ Penn Treebank Sample  
  76.   [ ] udhr................ Universal Declaration of Human Rights Corpus  
  77.   [ ] sample_grammars..... Sample Grammars  
  78.   [ ] book_grammars....... Grammars from NLTK Book  
  79.   [ ] spanish_grammars.... Grammars for Spanish  
  80.   [ ] wordnet............. WordNet  
  81.   [ ] wordnet_ic.......... WordNet-InfoContent  
  82.   [ ] words............... Word Lists  
  83.   [ ] tagsets............. Help on Tagsets  
  84.   [ ] basque_grammars..... Grammars for Basque  
  85.   [ ] large_grammars...... Large context-free and feature-based grammars  
  86.                            for parser comparison  
  87.   [ ] maxent_treebank_pos_tagger Treebank Part of Speech Tagger (Maximum entropy)  
  88.   [ ] rslp................ RSLP Stemmer (Removedor de Sufixos da Lingua  
  89.                            Portuguesa)  
  90.   [ ] hmm_treebank_pos_tagger Treebank Part of Speech Tagger (HMM)  
  91. Hit Enter to continue:   
  92.   [ ] punkt............... Punkt Tokenizer Models  
  93.   
  94. Collections:  
  95.   [ ] all-corpora......... All the corpora  
  96.   [ ] all................. All packages  
  97.   [ ] book................ Everything used in the NLTK Book  
  98.   
  99. ([*] marks installed packages)  



你可以选择敲入 all-corpora,或all,或book,我选的是all。保持网络畅通,下载可能需要一段时间。显示信息如下:

[java]  view plain  copy
  1. Download which package (l=list; x=cancel)?  
  2.   Identifier> all  
  3.     Downloading collection 'all'  
  4.        |   
  5.        | Downloading package 'abc' to C:\Documents and  
  6.        |     Settings\lenovo\Application Data\nltk_data...  
  7.        |   Unzipping corpora\abc.zip.  
  8.        | Downloading package 'alpino' to C:\Documents and  
  9.        |     Settings\lenovo\Application Data\nltk_data...  
  10.        |   Unzipping corpora\alpino.zip.  
  11.        | Downloading package 'biocreative_ppi' to C:\Documents and  
  12.        |     Settings\lenovo\Application Data\nltk_data...  
  13.        |   Unzipping corpora\biocreative_ppi.zip.  
  14.        | Downloading package 'brown' to C:\Documents and  
  15.        |     Settings\lenovo\Application Data\nltk_data...  
  16.        |   Unzipping corpora\brown.zip.  
  17.        | Downloading package 'brown_tei' to C:\Documents and  
  18.        |     Settings\lenovo\Application Data\nltk_data...  
  19.        |   Unzipping corpora\brown_tei.zip.  
  20.        | Downloading package 'cess_cat' to C:\Documents and  
  21.        |     Settings\lenovo\Application Data\nltk_data...  
  22.        |   Unzipping corpora\cess_cat.zip.  
  23.        | Downloading package 'cess_esp' to C:\Documents and  
  24.        |     Settings\lenovo\Application Data\nltk_data...  
  25.        |   Unzipping corpora\cess_esp.zip.  
  26.        | Downloading package 'chat80' to C:\Documents and  
  27.        ...  
  28.        ...  
  29.        ...  
  30.   
  31.        | Downloading package 'book_grammars' to C:\Documents and  
  32.        |     Settings\lenovo\Application Data\nltk_data...  
  33.        |   Unzipping grammars\book_grammars.zip.  
  34.        | Downloading package 'sample_grammars' to C:\Documents and  
  35.        |     Settings\lenovo\Application Data\nltk_data...  
  36.        |   Unzipping grammars\sample_grammars.zip.  
  37.        | Downloading package 'spanish_grammars' to C:\Documents and  
  38.        |     Settings\lenovo\Application Data\nltk_data...  
  39.        |   Unzipping grammars\spanish_grammars.zip.  
  40.        | Downloading package 'basque_grammars' to C:\Documents and  
  41.        |     Settings\lenovo\Application Data\nltk_data...  
  42.        |   Unzipping grammars\basque_grammars.zip.  
  43.        | Downloading package 'large_grammars' to C:\Documents and  
  44.        |     Settings\lenovo\Application Data\nltk_data...  
  45.        |   Unzipping grammars\large_grammars.zip.  
  46.        | Downloading package 'tagsets' to C:\Documents and  
  47.        |     Settings\lenovo\Application Data\nltk_data...  
  48.        |   
  49.      Done downloading collection 'all'  
  50. ---------------------------------------  
  51.     d) Download   l) List    u) Update   c) Config   h) Help   q) Quit  
  52. ---------------------------------------  
  53. Downloader>  


选择q,退出下载。

[java]  view plain  copy
  1. Downloader> q  
  2. True  


注1:在这个过程中,可以获取帮助,用h) Help,敲入:h。显示如下:

[java]  view plain  copy
  1. Downloader> h  
  2.   
  3. Commands:  
  4.   d) Download a package or collection     u) Update out of date packages  
  5.   l) List packages & collections          h) Help  
  6.   c) View & Modify Configuration          q) Quit  
  7.   
  8. ---------------------------------------  
  9.     d) Download   l) List    u) Update   c) Config   h) Help   q) Quit  
  10. ---------------------------------------  
  11. Downloader>  


注2:下载之前,可以选择下载到本地的路径,选择c) Config,敲入:c,进入Config环境。显示默认的下载路径,如下:

[java]  view plain  copy
  1. Downloader> c  
  2.   
  3. Data Server:  
  4.   - URL: <http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml>  
  5.   - 3 Package Collections Available  
  6.   - 74 Individual Packages Available  
  7.   
  8. Local Machine:  
  9.   - Data directory: C:\Documents and Settings\lenovo\Application Data\nltk_data  
  10.   
  11. ---------------------------------------  
  12.     s) Show Config   u) Set Server URL   d) Set Data Dir   m) Main Menu  
  13. ---------------------------------------  
  14. Config>  


选择d) Set Data Dir,敲入:d,键入新的下载路径:

[java]  view plain  copy
  1. Config> d  
  2.   New Directory> D:\nltk_data  
  3.   
  4. ---------------------------------------  
  5.     s) Show Config   u) Set Server URL   d) Set Data Dir   m) Main Menu  
  6. ---------------------------------------  
  7. Config>  


如果不改变下载路径,直接退出设置环境。

[java]  view plain  copy
  1. New Directory> q  
  2.   Cancelled!  
  3.   
  4. ---------------------------------------  
  5.     s) Show Config   u) Set Server URL   d) Set Data Dir   m) Main Menu  
  6. ---------------------------------------  
  7. Config>  


返回到主菜单:

[java]  view plain  copy
  1. Config> m  
  2.   
  3. ---------------------------------------  
  4.     d) Download   l) List    u) Update   c) Config   h) Help   q) Quit  
  5. ---------------------------------------  
  6. Downloader>  


退出下载环境:

[java]  view plain  copy
  1. Downloader> q  
  2. True  


注3:如果上述不成功的话,你可以直接到 http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml 去下载数据包,放到下载路径的目录下即可。

(四)测试NLTK数据包
导入nltk.book包中所有的东西:

[java]  view plain  copy
  1. >>> from nltk.book import *  


显示如下,表明NLTK数据成功装载。

[java]  view plain  copy
  1. >>> from nltk.book import *  
  2. *** Introductory Examples for the NLTK Book ***  
  3. Loading text1, ..., text9 and sent1, ..., sent9  
  4. Type the name of the text or sentence to view it.  
  5. Type: 'texts()' or 'sents()' to list the materials.  
  6. text1: Moby Dick by Herman Melville 1851  
  7. text2: Sense and Sensibility by Jane Austen 1811  
  8. text3: The Book of Genesis  
  9. text4: Inaugural Address Corpus  
  10. text5: Chat Corpus  
  11. text6: Monty Python and the Holy Grail  
  12. text7: Wall Street Journal  
  13. text8: Personals Corpus  
  14. text9: The Man Who Was Thursday by G . K . Chesterton 1908  
  15. >>>   


(五)开始NLP工作
运行《Python自然语言处理》(影印版)中的例子,检索含“monstrous”的句子,查询词居中显示:

[java]  view plain  copy
  1. >>> text1.concordance('monstrous')  
  2. Building index...  
  3. Displaying 11 of 11 matches:  
  4. ong the former , one was of a most monstrous size . ... This came towards us ,   
  5. ON OF THE PSALMS . " Touching that monstrous bulk of the whale or ork we have r  
  6. ll over with a heathenish array of monstrous clubs and spears . Some were thick  
  7. d as you gazed , and wondered what monstrous cannibal and savage could ever hav  
  8. that has survived the flood ; most monstrous and most mountainous ! That Himmal  
  9. they might scout at Moby Dick as a monstrous fable , or still worse and more de  
  10. th of Radney .'" CHAPTER 55 Of the Monstrous Pictures of Whales . I shall ere l  
  11. ing Scenes . In connexion with the monstrous pictures of whales , I am strongly  
  12. ere to enter upon those still more monstrous stories of them which are to be fo  
  13. ght have been rummaged out of this monstrous cabinet there is no telling . But   
  14. of Whale - Bones ; for Whales of a monstrous size are oftentimes cast up dead u  
  15. >>>  


再看几个例子。
查看语料库中的文本信息,直接敲它的名字:

[java]  view plain  copy
  1. >>> text1  
  2. <Text: Moby Dick by Herman Melville 1851>  


 

[java]  view plain  copy
  1. >>> text2  
  2. <Text: Sense and Sensibility by Jane Austen 1811>  


查看与检索词类似的词语:

[java]  view plain  copy
  1. >>> text1.similar('monstrous')  
  2. Building word-context index...  
  3. abundant candid careful christian contemptible curious delightfully  
  4. determined doleful domineering exasperate fearless few gamesome  
  5. horrible impalpable imperial lamentable lazy loving  


 

[java]  view plain  copy
  1. >>> text2.similar('monstrous')  
  2. Building word-context index...  
  3. very exceedingly heartily so a amazingly as extremely good great  
  4. remarkably sweet vast  


查看词语的分散度图:

[java]  view plain  copy
  1. >>> text4.dispersion_plot(['citizens','democracy','freedom','duties','America'])  
  2.   
  3. Traceback (most recent call last):  
  4.   File "<pyshell#12>", line 1, in <module>  
  5.     text4.dispersion_plot(['citizens','democracy','freedom','duties','America'])  
  6.   File "C:\Python27\lib\site-packages\nltk\text.py", line 454, in dispersion_plot  
  7.     dispersion_plot(self, words)  
  8.   File "C:\Python27\lib\site-packages\nltk\draw\dispersion.py", line 25, in   
  9.   
  10. dispersion_plot  
  11.     raise ValueError('The plot function requires the matplotlib package (aka pylab).'  
  12. ValueError: The plot function requires the matplotlib package (aka pylab).See   
  13.   
  14. http://matplotlib.sourceforge.net/  
  15. >>>  


注意到这里出错了,是因为找不到画图的工具包。按照提示,从(一)中所列的网站上下载、安装Matplotlib即可。我安装了NumPy和Matplotlib。显示如下图:

文本生成的例子:

[java]  view plain  copy
  1. >>> text3.generate()  
  2. Building ngram index...  
  3. In the six hundredth year of Noah , and Epher , and I put the stone  
  4. from the field , And Ophir , and laid him on the morrow , that thou  
  5. dost overtake them , and herb yielding seed after him that curseth  
  6. thee , of a tree yielding fruit after his kind , cattle , and spread  
  7. his tent , and Abimael , and Lot went out . The LORD God had taken  
  8. from our father is in the inn , he gathered up his hand . And say ye  
  9. moreover , Behold , I know that my  


查看文本中的词例(token)数:

[java]  view plain  copy
  1. >>> len(text3)  
  2. 44764  


查看文本中的词型(type)数,并按字母升序列出:

[java]  view plain  copy
  1. >>> sorted(set(text3))  
  2. ['!'"'", '(', ')', ',', ',)', '.', '.)', ':', ';', ';)', '?', '?)', 'A', 'Abel', 'Abelmizraim', 'Abidah', 'Abide', 'Abimael', 'Abimelech', 'Abr', 'Abrah', 'Abraham', 'Abram', 'Accad', 'Achbor', 'Adah', 'Adam', 'Adbeel', 'Admah', 'Adullamite', 'After', 'Aholibamah', 'Ahuzzath', 'Ajah', 'Akan', 'All', 'Allonbachuth', 'Almighty', 'Almodad', 'Also', 'Alvah', 'Alvan', 'Am', 'Amal', 'Amalek', 'Amalekites', 'Ammon', 'Amorite',...]  


好了,准备工作已经做完了,以后就可以开始进行各种各样的NLP工作了,特别是对于中文(汉语)的自然语言处理工作,《Python自然语言处理》(影印版)并没有给出特别的篇幅。看来,这些工作还得我们自己想办法解决啊。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于Python的中文自然语言处理可以分为多个方面,括文本处理、文本分词、词性标注、命名实体识别、句法分析、情感分析等。 首先,文本处理是中文自然语言处理的基础,可以使用Python中的字符串处理函数对中文文本进行清洗、分割和合并等操作,以便后续处理。 其次,文本分词是中文自然语言处理的重要环节,可以利用Python中的jieba库对中文文本进行分词,将文本按词语进行划分。 词性标注则是在文本分词的基础上,对每个词语进行词性标记,可以利用Python中的nltk库或Stanford CoreNLP等工具实现中文文本的词性标注。 命名实体识别是指在文本中识别出具有特定意义的实体,如人名、地名、组织机构名等,可以利用Python中的HanLP或LTP等工具进行中文文本的命名实体识别。 句法分析是对文本中的句子进行语法分析,分析句子中各个成分之间的关系,可以利用Python中的Stanford CoreNLP或LTP等工具进行中文文本的句法分析。 最后,情感分析是对文本中的情感倾向进行分析,可以利用Python中的情感分析库进行中文文本的情感分析,了解文本中所表达的情感态度。 综上所述,基于Python的中文自然语言处理涵盖了文本处理、文本分词、词性标注、命名实体识别、句法分析、情感分析等多个方面,可以有效地对中文文本进行语言处理和分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值