Forming Bigrams of words in list of sentences with Python

前端 未结 10 1413
遇见更好的自我
遇见更好的自我 2020-12-24 02:16

I have a list of sentences:

text = [\'cant railway station\',\'citadel hotel\',\' police stn\']. 

I need to form bigram pairs and store the

10条回答
  •  一生所求
    2020-12-24 02:40

    I think the best and most general way to do it is the following:

    n      = 2
    ngrams = []
    
    for l in L:
        for i in range(n,len(l)+1):
            ngrams.append(l[i-n:i])
    

    or in other words:

    ngrams = [ l[i-n:i] for l in L for i in range(n,len(l)+1) ]
    

    This should work for any n and any sequence l. If there are no ngrams of length n it returns the empty list.

提交回复
热议问题