python - nltk如何给出多个分隔的句子

标签 python list nested nested-lists flatten

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

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

为了运行

nltk.utils.ngram

我需要将列表扁平化为:

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

但是后来我在

中得到了一个错误 bgram

('one','hello')

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

谢谢!

最佳答案

试试这个:

from itertools import chain

sentences = list(chain(*sentences))

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

或者你可以这样做:

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

关于python - nltk如何给出多个分隔的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52606753/

相关文章:

python - 数据帧警告 : SettingWithCopyWarning in python

python - 如何动态更新Python循环中参数的值?

python - BeautifulSoup 忽略表内的嵌套表

python - 如何将单个元素加入到 Python 中的字符串列表中

python - 如何将与正则表达式匹配的所有字符串放入 Python 列表中?

python - 从 Pandas DataFrame 创建复杂的嵌套字典

python - 为什么 fmod(1.0,0.1) == .1?

c# - 多维整数列表 C#

javascript - 从嵌套数组中获取 json 数据

c# - MVC 中 javascript 中的嵌套 foreach