Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.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 难以找到工作正常的ngram文档_Python_N Gram - Fatal编程技术网

Python 难以找到工作正常的ngram文档

Python 难以找到工作正常的ngram文档,python,n-gram,Python,N Gram,我试图在python中使用ngram函数,但对于我正在处理的一个问题,我无法正确实现它 我试着插入ngram和ngram import nltk from nltk.util import ngrams def n_grams(words, min=2, max=3): s = [] for n in range(min, max): for ngram in ngrams(words, n): s.append(' '.join(str

我试图在python中使用ngram函数,但对于我正在处理的一个问题,我无法正确实现它

我试着插入ngram和ngram

import nltk
from nltk.util import ngrams

def n_grams(words, min=2, max=3):
    s = []
    for n in range(min, max):
        for ngram in ngrams(words, n):
            s.append(' '.join(str(i) for i in ngram))
    return s

t = 'hippopotomonstrosesquippedaliophobia'
t_split = re.split(r'\W*', t)
print(n_grams(t_split))
我试图返回以下内容:

#{'tr', 'ho', 'hi', 'to', 'om', 'io', 'ob', 'mo', 'ed', 'ip', 'al', 'bi', 'pe', 
#'da', 'po', 'ns', 'qu', 'st', 'ia', 'ot', 'se', 'op', 'ro', 'ui', 'li', 'pp', 
#'es', 'sq', 'ph', 'on', 'os'} 

but instead returning this:
#[' h', 'h i', 'i p', 'p p', 'p o', 'o p', 'p o', 'o t', 't o', 'o m', #'m o', 'o n', 'n s', 's t', 't r', 'r o', 'o s', 's e', 'e s', 's q', #'q u', 'u i', 'i p', 'p p', 'p e', 'e d', 'd a', 'a l', 'l i', 'i o', #'o p', 'p h', 'h o', 'o b', 'b i', 'i a', 'a ']

实际上,这里唯一的问题是多余的正则表达式和连接语法。您正在对匹配零到无限非单词字符([^a-zA-Z0-9])的模式调用re.split(),但实际上没有任何字符串与该模式匹配。它没有什么可拆分的,因此正则表达式返回的是整个单词未更改(并在Python 3.6+中抛出一个错误)。在一些Python解释器中进行测试,看起来它可能也在字符串的开头和结尾拆分,但这可能是您正在使用的版本或join语句(请参见下文)的产物——我无法从这段代码中判断

如果我像您编写的那样使用
n_grams
函数,但是在join中调用它时没有空格,而不是使用join,并且完全删除您的正则表达式,我认为它得到了您想要的结果(bigraph集):

即:

{'es', 'op', 'bi', 'hi', 'ot', 'ro', 'ph', 'al', 
 'ns', 'sq', 'ho', 'ed', 'ob', 'ip', 'to', 'io', 
 'on', 'da', 'pe', 'om', 'mo', 'ia', 'st', 'po', 
 'tr', 'qu', 'se', 'ui', 'pp', 'li', 'os'}
如果您选择从集合导入计数器
,则还可以获得以下信息:

print(Counter(n_grams(t)))
生成计数字典,基本上:

Counter({'ip': 2, 'pp': 2, 'po': 2, 'op': 2, 'hi': 1, 'ot': 1, 'to': 1, 'om': 
  1, 'mo': 1, 'on': 1, 'ns': 1, 'st': 1, 'tr': 1, 'ro': 1, 'os': 1, 'se': 1, 
  'es': 1, 'sq': 1, 'qu': 1, 'ui': 1, 'pe': 1, 'ed': 1, 'da': 1, 'al': 1, 'li': 
  1, 'io': 1, 'ph': 1, 'ho': 1, 'ob': 1, 'bi': 1, 'ia': 1})
要处理边缘字符,您可以告诉NLTK的ngram函数使用右和左填充,并指定字符(通常是
),但在本例中似乎没有必要这样做

Counter({'ip': 2, 'pp': 2, 'po': 2, 'op': 2, 'hi': 1, 'ot': 1, 'to': 1, 'om': 
  1, 'mo': 1, 'on': 1, 'ns': 1, 'st': 1, 'tr': 1, 'ro': 1, 'os': 1, 'se': 1, 
  'es': 1, 'sq': 1, 'qu': 1, 'ui': 1, 'pe': 1, 'ed': 1, 'da': 1, 'al': 1, 'li': 
  1, 'io': 1, 'ph': 1, 'ho': 1, 'ob': 1, 'bi': 1, 'ia': 1})