Python中的Tab格式嵌套字符串转换为嵌套列表

2024-09-30 06:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

你好伙计们,在用靓汤刮取数据后。。。 我想格式化这些数据,以便可以轻松地将其导出到CSV和JSON。在

我的问题是如何翻译这个问题:

Heading :
    Subheading :

AnotherHeading : 
    AnotherSubheading :
        Somedata

Heading :
    Subheading :

AnotherHeading : 
    AnotherSubheading :
        Somedata

进入这个

^{pr2}$

为清晰起见,缩进

任何营救尝试都会受到热烈的感谢!在

到目前为止,在我们的帮助下:

def parse(data):
  stack = [[]]
  levels = [0]
  current = stack[0]
  for line in data.splitlines():
    indent = len(line)-len(line.lstrip())
    if indent > levels[-1]:
      levels.append(indent)
      stack.append([])
      current.append(stack[-1])
      current = stack[-1]
    elif indent < levels[-1]:
      stack.pop()
      current = stack[-1]
      levels.pop()
    current.append(line.strip().rstrip(':'))
  return stack

这个代码的问题是它返回。。。在

[
'Heading ', 
['Subheading '], 
'AnotherHeading ', 
['AnotherSubheading ', ['Somedata'], 'Heading ', 'Subheading '], 'AnotherHeading ', 
['AnotherSubheading ', ['Somedata']]
]

这里是一个回复:https://repl.it/yvM/1


Tags: 数据datalenstacklinecurrentpoplevels
3条回答

比如:

def parse(data):
    stack = [[]]
    levels = [0]
    current = stack[0]
    for line in data.splitlines():
        indent = len(line)-len(line.lstrip())
        if indent > levels[-1]:
            levels.append(indent)
            stack.append([])
            current.append(stack[-1])
            current = stack[-1]
        elif indent < levels[-1]:
            stack.pop()
            current = stack[-1]
            levels.pop()
        current.append(line.strip().rstrip(':'))
    return stack[0]

不过,您的格式看起来很像YAML;您可能需要研究PyYAML。在

谢谢你们kirbyfan64sos和SuperBiasedMan

def parse(data):

  currentTab = 0
  currentList = []
  result = [currentList]

  i = 0
  tabCount = 0

  for line in data.splitlines():

    tabCount = len(line)-len(line.lstrip())

    line = line.strip().rstrip(' :')

    if tabCount == currentTab:
        currentList.append(line)

    elif tabCount > currentTab:
        newList = [line]
        currentList.append(newList)
        currentList = newList

    elif tabCount == 0:
        currentList = [line]
        result.append(currentList)

    elif tabCount == 1:
        currentList = [line]
        result[-1].append(currentList)

    currentTab = tabCount

    tabCount = tabCount + 1
    i = i + 1

  print(result)

首先,您希望清除不必要的空白,因此您需要列出包含空白以外的所有行的列表,并为主循环设置所有的默认值。在

teststring = [line for line in teststring.split('\n') if line.strip()]
currentTab = 0
currentList = []
result = [currentList]

此方法响应列表的可变性,因此将currentList设置为空列表,然后将result设置为{}是一个重要的步骤,因为我们现在可以附加到{}。在

^{pr2}$

这是我能想到的检查每行开头是否有制表符的最好方法。还有,是的,你会注意到我实际上检查了空格,而不是制表符。标签100%不起作用,我想是因为我用了更换因为我没有安装Python3。它在Python2.7上运行得非常好,但是我不会把我还没有验证过的代码放进去。如果您确认使用\t并删除tabCount /= 8会产生所需的结果,那么我可以编辑它。在

现在,检查行的缩进程度。如果它与我们的currentTab值相同,那么只需附加到currentList之后。在

    if tabCount == currentTab:
        currentList.append(line.strip())

如果它更高,那就意味着我们进入了更深层次的列表层次。我们需要一个嵌套在currentList中的新列表。在

    elif tabCount > currentTab:
        newList = [line.strip()]
        currentList.append(newList)
        currentList = newList

向后走比较困难,因为数据只包含3个嵌套级别,我选择硬编码如何处理值0和1(2应该总是产生上述块之一)。如果没有选项卡,我们可以在result上追加一个新列表。在

    elif tabCount == 0:
        currentList = [line.strip()]
        result.append(currentList)

对于一个单标签的深标题,基本上是相同的,除了你应该附加到result[-1],因为这是最后一个要嵌套的主标题。在

    elif tabCount == 1:
        currentList = [line.strip()]
        result[-1].append(currentList)

最后,确保currentTab更新为当前的tabCount,这样下一次迭代就可以正常运行了。在

    currentTab = tabCount

相关问题 更多 >

    热门问题