用python的NLTK计算动词、名词和其他词类

2024-06-01 03:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多篇课文,我想根据它们对名词和动词等不同词类的用法创建它们的简介。基本上,我需要计算每个词类的使用次数。

我已经标记了文本,但不确定如何进一步:

tokens = nltk.word_tokenize(text.lower())
text = nltk.Text(tokens)
tags = nltk.pos_tag(text)

如何将每个词性的计数保存为变量?


Tags: text标记文本用法动词次数lowerword
1条回答
网友
1楼 · 发布于 2024-06-01 03:33:50

pos_tag方法返回(标记、标记)对的列表:

tagged = [('the', 'DT'), ('dog', 'NN'), ('sees', 'VB'), ('the', 'DT'), ('cat', 'NN')] 

如果您使用的是Python2.7或更高版本,那么您只需使用:

>>> from collections import Counter
>>> counts = Counter(tag for word,tag in tagged)
>>> counts
Counter({'DT': 2, 'NN': 2, 'VB': 1})

要使计数正常化(给出每个计数的比例),请执行以下操作:

>>> total = sum(counts.values())
>>> dict((word, float(count)/total) for word,count in counts.items())
{'DT': 0.4, 'VB': 0.2, 'NN': 0.4}

注意,在较旧版本的Python中,您必须自己实现Counter

>>> from collections import defaultdict
>>> counts = defaultdict(int)
>>> for word, tag in tagged:
...  counts[tag] += 1

>>> counts
defaultdict(<type 'int'>, {'DT': 2, 'VB': 1, 'NN': 2})

相关问题 更多 >