Python文件解析:从文本文件构建树

Python文件解析:从文本文件构建树,第1张

Python文件解析:从文本文件构建树

最大的问题是“超前”,我认为这引起了问题。可以将其略微缩短:

def _recurse_tree(parent, depth, source):    last_line = source.readline().rstrip()    while last_line:        tabs = last_line.count('t')        if tabs < depth: break        node = last_line.strip()        if tabs >= depth: if parent is not None:     print "%s: %s" %(parent, node) last_line = _recurse_tree(node, tabs+1, source)    return last_lineinFile = open("test.txt")_recurse_tree(None, 0, inFile)

由于我们在谈论递归,因此我竭尽全力避免任何全局变量(

source
last_line
)。使它们成为某个解析器对象的成员将更加具有Pythonic性。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5652284.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存