Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将文本转换为嵌套列表_Python_Recursion_Nested Lists - Fatal编程技术网

Python 如何将文本转换为嵌套列表

Python 如何将文本转换为嵌套列表,python,recursion,nested-lists,Python,Recursion,Nested Lists,我试图将文本输入转换为保留其结构的嵌套列表。目前,我有一个函数,它获取文本和所需的“深度”,并输出一个该深度的嵌套列表,在每一个换行符、句子或单词处打断文本 def text_split(text, depth): depth_list = [' ', '.', '\n'] if isinstance(text, str): text = text.strip('. ') text = text.split(depth_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.

"""
进入

现在,这可能不是最好或最优雅的方法,而且它存在一些问题,例如在拆分
\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']],
 ...

为什么你想要所有的深度,例如,为什么列表中只有一个单词?@AChampion确实,这不需要维护结构!这不是要求。谢谢你指出!那就清楚多了!我选择了递归函数,因为我想我可能会在以后扩展我的深度列表,但仔细想想,我不认为它能比这个更深:P谢谢!没问题!如果答案回答了您的问题,请记住接受答案。我对文本中的行做了一些更改。splitlines():splits直接删除\n\n(无需进行长度检查)
如果删除,请执行以下操作:
比检查长度快(我希望结果相同)我接受你的答案,因为即使它比列表理解慢一点,它也更具可读性!再次感谢你的帮助:)谢谢你的帮助!我只添加了另一层理解,这样我就可以从单词中去掉诸如“,”之类的内容,并将
split('\n')
更改为
splitlines()
,因为它似乎更一般:
[[w.strip(',.;')表示s in s in s.split()表示s in line.split('.')if s]表示文本中的line.splitlines()

>>> [[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']],
 ...