python nltk 基本操作

分词

nltk.sent_tokenize(text) #按句子分割
nltk.word_tokenize(sentence) #分词
nltk的分词是句子级别的,所以对于一篇文档首先要将文章按句子进行分割,然后句子进行分词
这里写图片描述

词性标注

nltk.pos_tag(tokens) #对分词后的句子进行词性标注

tags = [nltk.pos_tag(tokens) for tokens in words]
>>>tags
[[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('text', 'NN'), ('for', 'IN'), ('test', 'NN'), ('.', '.')], [('And', 'CC'), ('I', 'PRP'), ('want', 'VBP'), ('to', 'TO'), ('learn', 'VB'), ('how', 'WRB'), ('to', 'TO'), ('use', 'VB'), ('nltk', 'NN'), ('.', '.')]]

分块 Chunking

用于实体识别的基本技术是分块,可以理解为把对个token组成词组。

名词短语分块

NP-chunking,寻找单独名词短语对应的块。为了创建NP分块,首先需要定义分块语法,规定句子如何分块。下面使用的是一个简单的正则,这条规则规定由可选的且后面跟着任意数量形容词(JJ)的限定词(DJ)和名词(NN)组成。

>>> text = "the little yellow dog barked at the cat"
>>> sentence = nltk.word_tokenize(text)
>>> sentence = nltk.pos_tag(sentence)
>>> sentence
[('the', 'DT'), ('little', 'JJ'), ('yellow', 'NN'), ('dog', 'NN'), ('barked', 'VBD'), ('at', 'IN'), ('the', 'DT'), ('cat', 'NN')]
>>> grammar = "NP: {<DT>?<JJ>*<NN>}"
>>> cp = nltk.RegexpParser(grammar)
>>> result = cp.parse(sentence)
>>> result
Tree('S', [Tree('NP', [('the', 'DT'), ('little', 'JJ'), ('yellow', 'NN')]), Tree('NP', [('dog', 'NN')]), ('barked', 'VBD'), ('at', 'IN'), Tree('NP', [('the', 'DT'), ('cat', 'NN')])])
>>> result.draw()

命名实体识别

ref: http://www.pythontip.com/blog/post/10012/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章