我正在学习python。这也是我的第一个stackoverflow问题,并努力格式化输出以显示我的要求。我正在编写python代码,用于将带逗号分隔值的字符串转换为级别层次结构显示数据,如下所示。
s = "(id,cb,e(id,fn,eT(id), ln),lc)"
我想要这样的输出
-id
-cb
-e
--id
--fn
--eT
---id
--ln
-lc
到目前为止,我已经做了一些编码,但我正在努力改进它。
class parent-child():
stack = []
def tree_recur(self,employee, level):
s = s[s.index("(")+1:s.rindex(")")]
ind = 0
while(s.rstrip != null or s != ""):
ss = s.index(",")
words = s[ind:ss]
parenind = words.index("(")
if parenind == -1:
stack.append(level,words)
s = s[ss+1:len(s)]
else:
stack.append(s[ss+1:parenind-1])
closeparenind = s.index(")")
ss1= s[parenind:closeparenind]
return tree_recur(self,ss1,level+1)
def main():
s = "(id,created,employee(id,firstname,employeeType(id), lastname),location)"
level = 0
print(E = parent-child(s, level))
main()
有人可以帮我改进这段代码。我不知道如何在字符串之前打印“ - ”取决于级别的深度。这是1级连字符,2级连字符,3级连字符3,当括号关闭时向上移动。我要感谢你的帮助和花在帮助我的时间。
既然你已经在尝试解析了。更简单的方法是迭代每个字符。
s = "(id,cb,e(id,fn,eT(id), ln),lc)"
hyphens = 0
result = []
current = ""
for c in s:
if c == "(": hyphens += 1
if c == ")": hyphens -= 1
if c.isalnum():
if not current:
current += "-" * hyphens
current += c
elif current:
result.append(current)
current = ""
result = " ".join(result)
print(result)
哪个印刷品:
-id -cb -e --id --fn --eT ---id --ln -lc
编辑:
我能理解你想要这种格式:
-id
-cb
-e
--id
--fn
--eT
---id
--ln
-lc
这可以通过更改:
current += " " * 2 * (hyphens - 1) + "-" * hyphens
和
result = "\n".join(result)