如何使用spacy找到最常用的单词?

我使用Python的spacy和它的工作正常标记每个单词,但我想知道是否有可能找到一个字符串中最常见的单词。 还有可能获得最常见的名词,动词,副词等吗?

有一个count_by函数,但我似乎无法让它以任何有意义的方式运行。


这看起来应该和Python中的其他任何东西一样。 spaCy允许您迭代文档,并返回一系列令牌对象。 这些可用于访问注释。

from __future__ import print_function, unicode_literals
import spacy
from collections import defaultdict, Counter

nlp = spacy.load('en')

pos_counts = defaultdict(Counter)
doc = nlp(u'My text here.')

for token in doc:
    pos_counts[token.pos][token.orth] += 1

for pos_id, counts in sorted(pos_counts.items()):
    pos = doc.vocab.strings[pos_id]
    for orth_id, count in counts.most_common():
        print(pos, count, doc.vocab.strings[orth_id])

请注意,.orth和.pos属性是整数。 您可以通过.orth_和.pos_属性获取它们映射的字符串。 .orth属性是令牌的非标准化视图,还有.lower,.lemma等字符串视图。 你可能想绑定一个.norm函数来做你自己的字符串规范化。 有关详细信息,请参阅文档。

整数对于您的计数很有用,因为如果您计算的是大型语料库,则可以使计数程序更加高效地存储内存。 您还可以将频繁计数存储在一个numpy数组中,以提高速度和效率。 如果你不想打扰这个,可以直接用.orth_属性来计算,或者使用别名.text。

请注意,上面代码片段中的.pos属性提供了一组粗糙的词性标签。 更丰富的树库标签在.tag属性中可用。


我最近不得不计算文本文件中所有令牌的频率。 您可以使用pos_属性过滤出单词以获得您喜欢的POS令牌。 这是一个简单的例子:

import spacy
from collections import Counter
nlp = spacy.load('en')
doc = nlp(u'Your text here')
# all tokens that arent stop words or punctuations
words = [token.text for token in self.doc if token.is_stop != True and token.is_punct != True]

# noun tokens that arent stop words or punctuations
nouns = [token.text for token in self.doc if token.is_stop != True and token.is_punct != True and token.pos_ == "NOUN"]

# five most common tokens
word_freq = Counter(words)
common_words = word_freq.most_common(5)

# five most common noun tokens
noun_freq = Counter(nouns)
common_nouns = noun_freq.most_common(5)
链接地址: http://www.djcxy.com/p/54173.html

上一篇: How to find the most common words using spacy?

下一篇: Something like django signals in Odoo