你好伙计们,在用靓汤刮取数据后。。。 我想格式化这些数据,以便可以轻松地将其导出到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
比如:
不过,您的格式看起来很像YAML;您可能需要研究PyYAML。在
谢谢你们kirbyfan64sos和SuperBiasedMan
首先,您希望清除不必要的空白,因此您需要列出包含空白以外的所有行的列表,并为主循环设置所有的默认值。在
此方法响应列表的可变性,因此将}是一个重要的步骤,因为我们现在可以附加到{}。在
^{pr2}$currentList
设置为空列表,然后将result
设置为{这是我能想到的检查每行开头是否有制表符的最好方法。还有,是的,你会注意到我实际上检查了空格,而不是制表符。标签100%不起作用,我想是因为我用了更换因为我没有安装Python3。它在Python2.7上运行得非常好,但是我不会把我还没有验证过的代码放进去。如果您确认使用
\t
并删除tabCount /= 8
会产生所需的结果,那么我可以编辑它。在现在,检查行的缩进程度。如果它与我们的
currentTab
值相同,那么只需附加到currentList
之后。在如果它更高,那就意味着我们进入了更深层次的列表层次。我们需要一个嵌套在
currentList
中的新列表。在向后走比较困难,因为数据只包含3个嵌套级别,我选择硬编码如何处理值0和1(2应该总是产生上述块之一)。如果没有选项卡,我们可以在
result
上追加一个新列表。在对于一个单标签的深标题,基本上是相同的,除了你应该附加到
result[-1]
,因为这是最后一个要嵌套的主标题。在最后,确保
currentTab
更新为当前的tabCount
,这样下一次迭代就可以正常运行了。在相关问题 更多 >
编程相关推荐