Skip to main content
 首页 » 编程设计

python之如何找到 ngram 在句子中的位置

2025年05月04日33zhengyun_ustc

有没有办法找到 ngram 在句子中的第一个位置?

>>> from nltk import ngrams 
>>> hyp = ['he', 'read', 'the', 'book', 'because', 'he', 'was', 'interested', 'in', 'world', 'history'] 
>>> position_of_ngram(('the', 'book'), hyp) 
2 

目前,我正在使用一些字符串技巧:

>>> " ".join(hyp)[:" ".join(hyp).index(" ".join(('the', 'book')))].count(' ') 
2 

但是有没有一种不需要愚蠢的字符串转换的方法?如果是这样,与“字符串/正则表达式 hack”相比,这是一种更快的方法吗?

请您参考如下方法:

为什么要自己搜索?这就是列表方法 index() 的用途:

def ngram_index(words, ngram): 
    return list(nltk.ngrams(words, len(ngram))).index(tuple(ngram))