【问题标题】:nltk how to give multiple separated sentencesnltk如何给出多个分隔的句子
【发布时间】:2019-03-07 11:40:48
【问题描述】:

我有英文句子列表(每个句子都是一个列表),我想获取 ngrams。 例如:

sentences = [['this', 'is', 'sentence', 'one'], ['hello','again']]

为了运行

nltk.utils.ngram

我需要将列表扁平化为:

sentences = ['this','is','sentence','one','hello','again']

但是我在

中得到了一个错误的bgram

('一','你好')

。 最好的处理方法是什么?

谢谢!

【问题讨论】:

    标签: python list nested nested-lists flatten


    【解决方案1】:

    试试这个:

    from itertools import chain
    
    sentences = list(chain(*sentences))
    

    chain 返回一个链对象,其.__next__() 方法从第一个可迭代对象返回元素,直到它用完,然后从下一个可迭代对象返回元素 可迭代,直到所有可迭代对象都用完为止。

    或者你可以这样做:

     sentences = [i for s in sentences for i in s]
    

    【讨论】:

    • 实际需要的链(*句子),效果很好,谢谢
    【解决方案2】:

    你也可以使用列表推导

    f = []
    [f.extend(_l) for _l in sentences]
    
    f = ['this', 'is', 'sentence', 'one', 'hello', 'again']
    

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 2018-04-26
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多