Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中使用n-gram分析获得短语的排序频率?_Python_Scikit Learn_Nltk - Fatal编程技术网

如何在Python中使用n-gram分析获得短语的排序频率?

如何在Python中使用n-gram分析获得短语的排序频率?,python,scikit-learn,nltk,Python,Scikit Learn,Nltk,我有一个文件,“filename.txt”。我需要得到所有的n-gram,比如说三角图,以及它们的频率,以一种分类的方式。我的目标基本上是获得最常用的短语 如何使用nltk/scikit学习实现这一点?这里有一个没有nltk的解决方案: from collections import deque def window(seq, n=3): it = iter(seq) win = deque((next(it, None) for _ in xrange(n-1)), maxl

我有一个文件,“filename.txt”。我需要得到所有的n-gram,比如说三角图,以及它们的频率,以一种分类的方式。我的目标基本上是获得最常用的短语


如何使用nltk/scikit学习实现这一点?

这里有一个没有nltk的解决方案:

from collections import deque

def window(seq, n=3):
    it = iter(seq)
    win = deque((next(it, None) for _ in xrange(n-1)), maxlen=n)
    for e in it: 
        win.append(e)
        yield tuple(win)

def sorted_grams(doc, n=3):
    counts = {}
    for ngram in window(doc, n): 
        counts[ngram] = counts.get(ngram, 0) + 1 

    return sorted(((v,k) for k,v in counts.items()), reverse=True)


example_doc = 'it is a small world after all it is a small world after all'
for s in sorted_grams(example_doc.split(), 3): 
    print s

到目前为止你尝试了什么?可能是重复的