Zac*_*ach 18 python tagging nlp nltk part-of-speech
我有多个文本,我想根据各种词性的使用来创建它们的配置文件,如名词和动词.基本上,我需要计算每个词性的使用次数.
我已经标记了文字,但我不确定如何进一步:
tokens = nltk.word_tokenize(text.lower())
text = nltk.Text(tokens)
tags = nltk.pos_tag(text)
Run Code Online (Sandbox Code Playgroud)
如何将每个词性的计数保存到变量中?
dhg*_*dhg 30
该pos_tag方法为您提供(令牌,标记)对的列表:
tagged = [('the', 'DT'), ('dog', 'NN'), ('sees', 'VB'), ('the', 'DT'), ('cat', 'NN')]
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python 2.7或更高版本,那么您只需使用以下命令即可:
>>> from collections import Counter
>>> counts = Counter(tag for word,tag in tagged)
>>> counts
Counter({'DT': 2, 'NN': 2, 'VB': 1})
Run Code Online (Sandbox Code Playgroud)
要规范化计数(给出每个的比例),请执行以下操作:
>>> total = sum(counts.values())
>>> dict((word, float(count)/total) for word,count in counts.items())
{'DT': 0.4, 'VB': 0.2, 'NN': 0.4}
Run Code Online (Sandbox Code Playgroud)
请注意,在旧版本的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})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15707 次 |
| 最近记录: |