【问题标题】:Create vocabulary dictionary for text mining为文本挖掘创建词汇词典
【发布时间】:2017-06-01 15:07:19
【问题描述】:

我有以下代码:

train_set = ("The sky is blue.", "The sun is bright.")
test_set = ("The sun in the sky is bright.",
    "We can see the shining sun, the bright sun.")

现在我尝试像这样计算词频:

    from sklearn.feature_extraction.text import CountVectorizer
    vectorizer = CountVectorizer()

接下来我想打印词汇表。所以我这样做:

vectorizer.fit_transform(train_set)
print vectorizer.vocabulary

现在我没有得到任何输出。虽然我期望类似:

{'blue': 0, 'sun': 1, 'bright': 2, 'sky': 3}

有什么想法会出错吗?

【问题讨论】:

标签: python nlp text-mining


【解决方案1】:

我想你可以尝试这个:

print vectorizer.vocabulary_

【讨论】:

    【解决方案2】:

    CountVectorizer 不支持您要查找的内容。

    您可以使用Counter 类:

    from collections import Counter
    
    train_set = ("The sky is blue.", "The sun is bright.")
    word_counter = Counter()
    for s in train_set:
        word_counter.update(s.split())
    
    print(word_counter)
    

    给予

    Counter({'is': 2, 'The': 2, 'blue.': 1, 'bright.': 1, 'sky': 1, 'sun': 1})
    

    或者你可以使用来自 nltk 的FreqDist:

    from nltk import FreqDist
    
    train_set = ("The sky is blue.", "The sun is bright.")
    word_dist = FreqDist()
    for s in train_set:
        word_dist.update(s.split())
    
    print(dict(word_dist))
    

    给予

    {'blue.': 1, 'bright.': 1, 'is': 2, 'sky': 1, 'sun': 1, 'The': 2}
    

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2015-01-10
      相关资源
      最近更新 更多