【问题标题】:Compute the term frequency–inverse document frequency with NLTK使用 NLTK 计算词频-逆文档频率
【发布时间】:2017-05-19 20:38:52
【问题描述】:

我正在使用 NLTK 来计算单词的 tf_idf。但大部分都是0分。

def compute_tf_idf(corpus,source_text):
    texts = []
    for text in corpus:
        if text['text'] != None:
            try:
                language = detect_lang(text['text'])
            except Exception as e:
                language = None
            # French analysing
            if language == "french":
                french_analyser = AnalyseFrenchText(text['text'])
                french_analyser.analysetext()
                tokenized_text = french_analyser.get_tokenized_text()
            if tokenized_text != None:
                texts.append(tokenized_text)
    textCorpus = TextCollection(texts)
    for word in textCorpus[:100]:
        print(word) # print correctly words
    try:
        language = detect_lang(source_text)
    except Exception as e:
        language = None
    # French analysing
    if language == "french":
        french_analyser = AnalyseFrenchText(source_text)
        french_analyser.analysetext()
        tokenized_source_text = french_analyser.get_tokenized_text()
    for word in tokenized_source_text:
        print(word)
        print("idf :" + str(textCorpus.idf(word)))
        print("tf : " + str(textCorpus.tf(word,tokenized_source_text)))
        print("tf_idf :" + str(textCorpus.tf_idf(word,tokenized_source_text)))
    return

结果:

Commande
idf :0.0
tf : 0.0024875621890547263
tf_idf :0.0

我检查了用于计算 idf 的 NLTK 源:

 """ The number of texts in the corpus divided by the
    number of texts that the term appears in.
    If a term does not appear in the corpus, 0.0 is returned. """

我用错了 NLTK 的 tf_idf 吗? 谢谢

【问题讨论】:

  • 您能发布完整代码或代码链接吗?目前,鉴于您发布的代码 sn-p ,尚不清楚问题可能出在哪里。另外,如果可能的话,将您的语料库样本发布在某个地方,否则也不清楚。

标签: python python-3.x nlp nltk


【解决方案1】:

您正在使用nltk 的 TF-IDF 计算实现,所以我不确定您的意思是“我应该改变什么以获得最佳 tf_idf 分数”。你可以改变的不是猜测;找出你的TextCollection的内容是什么样的,它是否认为“succursales”在里面等等。

您可以像这样检查一个单词是否在TextCollectionTrueFalse)中:

print("succursales" in mytexts)

要了解mytexts 中的实际内容,您可以这样迭代:

for word in mytexts[:100]:
    print(word)

我猜你会看到单个字母。 TextCollection 的构造函数需要一个标记(单词)列表,但看起来你没有这样做。

您还需要将标记列表传递给tf(),它应该是语料库中的一个文档,而不是整个语料库。但是您正在传递某种语料库对象。换句话说,阅读文档以便了解这些函数的用途以及如何调用它们。

【讨论】:

  • 您好,感谢您花时间帮助我。我更新了我的问题以反映您的意见。你能验证我是否做得对吗?谢谢
  • 1.修正你的缩进。 2. 显示source_text 来自哪里以及它的样子(不,不是原始文本本身,而是变量的内容。) 3. 你真的有for word in tokenized_source_text: 并且你得到one的数据> 输出中的单词?
  • source_text 是一个包含全文的字符串。输出要长得多,所有来自 source_text 的单词都会被计算出来。
猜你喜欢
  • 2014-05-18
  • 1970-01-01
  • 2016-01-23
  • 2015-01-19
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 2017-06-13
相关资源
最近更新 更多