gpt4 book ai didi

将嵌套缩进文本解析为列表

转载 作者:行者123 更新时间:2023-12-02 14:27:51 24 4
gpt4 key购买 nike

将嵌套缩进文本解析到列表中

嗨,

也许有人可以给我一个开始的帮助。

我嵌套了与此类似的缩进txt。我应该将其解析为嵌套列表结构,例如

TXT = r"""
Test1
NeedHelp
GotStuck
Sometime
NoLuck
NeedHelp2
StillStuck
GoodLuck
"""

Nested_Lists = ['Test1',
['NeedHelp',
['GotStuck',
['Sometime',
'NoLuck']]],
['NeedHelp2',
['StillStuck',
'GoodLuck']]
]

Nested_Lists = ['Test1', ['NeedHelp', ['GotStuck', ['Sometime', 'NoLuck']]], ['NeedHelp2', ['StillStuck', 'GoodLuck']]]

任何有关 python3 的帮助都会被采纳

最佳答案

您可以利用 Python 分词器来解析缩进的文本:

from tokenize import NAME, INDENT, DEDENT, tokenize

def parse(file):
stack = [[]]
lastindent = len(stack)

def push_new_list():
stack[-1].append([])
stack.append(stack[-1][-1])
return len(stack)

for t in tokenize(file.readline):
if t.type == NAME:
if lastindent != len(stack):
stack.pop()
lastindent = push_new_list()
stack[-1].append(t.string) # add to current list
elif t.type == INDENT:
lastindent = push_new_list()
elif t.type == DEDENT:
stack.pop()
return stack[-1]

示例:

from io import BytesIO
from pprint import pprint
pprint(parse(BytesIO(TXT.encode('utf-8'))), width=20)

输出

['Test1',
['NeedHelp',
['GotStuck',
['Sometime',
'NoLuck']]],
['NeedHelp2',
['StillStuck',
'GoodLuck']]]

关于将嵌套缩进文本解析为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22549478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com