2024-06-01 03:33:50 发布
网友
我有多篇课文,我想根据它们对名词和动词等不同词类的用法创建它们的简介。基本上,我需要计算每个词类的使用次数。
我已经标记了文本,但不确定如何进一步:
tokens = nltk.word_tokenize(text.lower()) text = nltk.Text(tokens) tags = nltk.pos_tag(text)
如何将每个词性的计数保存为变量?
pos_tag方法返回(标记、标记)对的列表:
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:
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})
pos_tag
方法返回(标记、标记)对的列表:如果您使用的是Python2.7或更高版本,那么您只需使用:
要使计数正常化(给出每个计数的比例),请执行以下操作:
注意,在较旧版本的Python中,您必须自己实现
Counter
:相关问题 更多 >
编程相关推荐