要約すれば
SO question: Python file parsing: Build tree from text fileの関数を使用して、テキスト ファイル入力からツリー構造を作成しています。しかし、グローバル変数を使用してのみツリーを作成でき、これを回避する方法が見つかりません。
入力データ
というファイルdata.txt
には、次のものがあります。
Root
-A 10
-B
--B A 2
--B B 5
--B Z 9
--B X
---X 4
---Y
----Y0 67
----Y1 32
---Z 3
-C 19
望ましい結果
{'B': ['B A 2', 'B B 5', 'B Z 9', 'B X'],
'B X': ['X 4', 'Y', 'Z 3'],
'Root': ['A 10', 'B', 'C 19'],
'Y': ['Y0 67', 'Y1 32']}
マイコード
import re, pprint
PATTERN = re.compile('^[-]+')
tree = {}
def _recurse_tree(parent, depth, source):
last_line = source.readline().rstrip()
while last_line:
if last_line.startswith('-'):
tabs = len( re.match(PATTERN, last_line).group() )
else:
tabs = 0
if tabs < depth:
break
node = re.sub(PATTERN, '', last_line.strip())
if tabs >= depth:
if parent is not None:
print "%s: %s" %(parent, node)
if parent in tree:
tree[parent].append(node)
else:
tree[parent] = [ node, ]
last_line = _recurse_tree(node, tabs+1, source)
return last_line
def main():
inFile = open("data.txt")
_recurse_tree(None, 0, inFile)
pprint.pprint(tree)
if __name__ == "__main__":
main()
問題
グローバル変数を取り除くにはどうすればよいですtree
か? 私が行うすべてのことは、コードをはるかに長くまたは醜くするように見えますが、関数を頻繁に使用したいので、コア結果の副作用に依存するのは嫌いです。
補足
以下の回答の後、次の方法で を返すようにコードを修正しtree
ました。これはpythonicですか?タプルを返してから最初の要素を捨てるのは、洗練されていないように思えます。
def _recurse_tree(parent, depth, source, tree=None):
if tree is None:
tree = {}
last_line = source.readline().rstrip()
while last_line:
if last_line.startswith('-'):
tabs = len( re.match(PATTERN, last_line).group() )
else:
tabs = 0
if tabs < depth:
break
node = re.sub(PATTERN, '', last_line.strip())
if tabs >= depth:
if parent is not None:
print "%s: %s" %(parent, node)
if parent in tree:
tree[parent].append(node)
else:
tree[parent] = [ node, ]
last_line, tree = _recurse_tree(node, tabs+1, source, tree)
return last_line, tree
def main():
inFile = open("data.txt")
tmp, tree = _recurse_tree(None, 0, inFile)
pprint.pprint(tree)