NLTK 二元组查找器的问题

3 投票
1 回答
2372 浏览
提问于 2025-04-17 14:24

我有一个名为 "all.txt" 的文本文件,里面包含了一段普通的英文段落。

但是当我运行这段代码时:

    import nltk
    from nltk.collocations import *
    bigram_measures = nltk.collocations.BigramAssocMeasures()
    trigram_measures = nltk.collocations.TrigramAssocMeasures()

    # change this to read in your data                                                                                                                                                   
    finder = BigramCollocationFinder.from_words(('all.txt'))

    # only bigrams that appear 3+ times                                                                                                                                                  
    #finder.apply_freq_filter(3)                                                                                                                                                         

    # return the 10 n-grams with the highest PMI                                                                                                                                         
    print finder.nbest(bigram_measures.pmi, 10)

我得到的结果是:

       [('.', 't'), ('a', 'l'), ('l', '.'), ('t', 'x'), ('x', 't')]

我哪里出错了?因为我只得到了字母,而我想要的是单词,不是字母!

这里有一个 "all.txt" 文件里的内容示例,帮助你理解正在处理的内容: "而不仅仅是民主党人反对这个计划。全国各地的美国人都表达了对这个计划的反对。我的民主党同事和我有一个更好的计划,可以加强道德规则,以提高国会的问责制,并确保立法得到适当的考虑。共和党的计划未能堵住一个漏洞,这个漏洞允许在成员们还没读过立法之前就进行考虑。"

1 个回答

5

第一个问题是,你并没有真正读取文件,而只是把一个包含文件路径的字符串传给了函数。第二个问题是,你需要先使用一个分词器。要解决第二个问题:

from nltk.tokenize import word_tokenize
finder = BigramCollocationFinder.from_words(word_tokenize("This is a test sentence"))
print finder.nbest(bigram_measures.pmi, 10)

这样会得到 [('This', 'is'), ('a', 'test'), ('is', 'a'), ('test', 'sentence')]

注意,你可能想用不同的分词器——可以查看 tokenize 包的文档,里面会详细解释各种选项。

至于第一个问题,你可以使用类似下面的代码:

with open('all.txt', 'r') as data_file:
    finder = BigramCollocationFinder.from_words(word_tokenize(data_file.read())

撰写回答