简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
将一个句子或者一个段落输入到 NLTK 相应的模块,该模块可以将这个句子或段落中的每个单词标注上其相应的词性,如动词、名词、形容词、副词等。
使用 NLTK 进行词性标注的代码如下:
import nltk document = 'Whether you\'re new to programming or an experienced
developer, it\'s easy to learn and use Python.' sentences =
nltk.sent_tokenize(document) for sent in sentences:
print(nltk.pos_tag(nltk.word_tokenize(sent)))
输出结果为:
[('Whether', 'IN'), ('you', 'PRP'), ("'re", 'VBP'), ('new', 'JJ'), ('to',
'TO'), ('programming', 'VBG'), ('or', 'CC'), ('an', 'DT'), ('experienced',
'JJ'), ('developer', 'NN'), (',', ','), ('it', 'PRP'), ("'s", 'VBZ'), ('easy',
'JJ'), ('to', 'TO'), ('learn', 'VB'), ('and', 'CC'), ('use', 'VB'), ('Python',
'NNP'), ('.', '.')]
大家可能不熟悉这里词性的表示方式,现将相应的词性表示方式列举如下:
CC 并列连词 NNS 名词复数 UH 感叹词 CD 基数词 NNP 专有名词 VB 动词原型 DT 限定符 NNP 专有名词复数 VBD 动词过去式 EX
存在词 PDT 前置限定词 VBG 动名词或现在分词 FW 外来词 POS 所有格结尾 VBN 动词过去分词 IN 介词或从属连词 PRP 人称代词 VBP
非第三人称单数的现在时 JJ 形容词 PRP$ 所有格代词 VBZ 第三人称单数的现在时 JJR 比较级的形容词 RB 副词 WDT 以wh开头的限定词
JJS 最高级的形容词 RBR 副词比较级 WP 以wh开头的代词 LS 列表项标记 RBS 副词最高级 WP$ 以wh开头的所有格代词 MD 情态动词 RP
小品词 WRB 以wh开头的副词 NN 名词单数 SYM 符号 TO to
词性标注过后,我们可以通过单词的词性来过滤出相应的数据,如我们要过滤出词性为 NNP 的单词,代码如下:
import nltk document = 'Today the Netherlands celebrates King\'s Day. To honor
this tradition, the Dutch embassy in San Francisco invited me to' sentences =
nltk.sent_tokenize(document) data = [] for sent in sentences: data = data +
nltk.pos_tag(nltk.word_tokenize(sent)) for word in data: if 'NNP' == word[1]:
print(word)
执行结果如下:
('Netherlands', 'NNP') ('King', 'NNP') ('Day', 'NNP') ('San', 'NNP')
('Francisco', 'NNP')
多说一点:
有了词性标注之后,在后续的文本处理过程中会有更多的线索供我们使用。
相关文档
Category: NLTK <https://pythonspot.com/category/nltk/>
上一篇:NLTK(一):英文分词分句 <https://www.jianshu.com/p/4fb3e3c9bd69>
下一篇:NLTK(三):使用模型做预测 <https://www.jianshu.com/p/11b44bd40af8>
热门工具 换一换