当前位置:   article > 正文

python nltk 基本操作_python nltk grammar

python nltk grammar

分词

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'), ('.', '.')]]
  • 1
  • 2
  • 3

分块 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

命名实体识别

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/242567
推荐阅读
相关标签
  

闽ICP备14008679号