如何将文本变成嵌套列表

how to turn text into nested list

我正在尝试将文本输入转换为保留其结构的嵌套列表。目前我有一个函数,它接受一个文本和一个想要的 "depth" 并输出一个这个深度的嵌套列表,在每个换行符、句子或单词处打破文本。

def text_split(text, depth):
    depth_list = [' ', '.', '\n']
    if isinstance(text, str):
        text = text.strip('. ')
        text = text.split(depth_list[depth])
    if depth >= 0:
        depth -= 1
        for ix, item in enumerate(text):
                item = item.strip('. ')
                text[ix] = text_split(item, depth)
    return text

这需要像

这样的文本
text1 = """acabei de ler um livro. um diário.
mas a liberdade sempre chamou fountaine mais forte.
a cada viagem fountaine ía mais longe. aprendeu a andar de bicicleta e viajou o sul da frança.

esse é o tipo de pergunta feita na última edição do prêmio Loebner, em que participantes precisam responder à algumas questões feitas pelo júri.

o que tem de especial nessa competição é que ela não é para humanos, mas sim para robôs. o prêmio Loebner é uma implementação do teste de Turing.

"""

进入

[   [[['acabei'], ['de'], ['ler'], ['um'], ['livro']], [['um'], ['diário']]],
[   [   ['mas'],
        ['a'],
        ['liberdade'],
        ['sempre'],
        ['chamou'],
        ['fountaine'],
        ['mais'],
        ['forte']]],
[   [   ['a'],
        ['cada'],
        ['viagem'],
        ['fountaine'],
        ['ía'],
        ['mais'],
        ['longe']],
    [   ['aprendeu'],
        ['a'],
        ['andar'],
        ['de'],
        ['bicicleta'],
        ['e'],
        ['viajou'],
        ['o'],
        ['sul'],
        ['da'],
        ['frança']]],
[[['']]], ... ]]]]

现在这可能不是最好或最优雅的方法,而且它有一些问题,例如 [[['']]]\n 拆分后出现(可以解决的问题通过使用 .splitlines(),但我找不到在递归函数中调用此方法的好方法。

执行此操作的更好方法是什么?我应该使用嵌套列表吗? (我打算在之后进行迭代)。谢谢指教!

这是我能想到的最适合您的要求:

text = []
for line in text1.split('\n'):
  sentences = []
  for sentence in line.split('.'):
    words = []
    for word in sentence.split(' '):
      if len(word.strip()) > 0: # make sure we are adding something
        words.append(word.strip())
    if len(words) > 0:
      sentences.append(words)
  if len(sentences) > 0:
    text.append(sentences)

使用这个,我们有一个明确定义的数组结构,我们可以确定我们没有任何空白或空数组。此外,在这里使用递归也不是一件好事,因为文本应该有一个清晰的结构。你知道递归不会达到超过 3 级的深度。

另外,如果你想要递归版本,你应该在你的问题中说明并明确要求。

您可以使用嵌套列表理解,只需使用您的拆分标准:

>>> [[s.split() for s in line.split('.') if s] for line in text1.split('\n') if line]
[[['acabei', 'de', 'ler', 'um', 'livro'], ['um', 'diário']],
 [['mas', 'a', 'liberdade', 'sempre', 'chamou', 'fountaine', 'mais', 'forte']],
 [['a', 'cada', 'viagem', 'fountaine', 'ía', 'mais', 'longe'],
  ['aprendeu', 'a', 'andar', 'de', 'bicicleta', 'e', 'viajou', 'o', 'sul', 'da', 'frança']],
 ...