Reputation: 97
I'm an beginner with python, and i'm trying to do some data analysis using it. I've got a text file which looks like this:
top1
top1_a
top1_b
top1_c
top1_c_a
top1_c_a_a
top1_c_a_b
top1_d
top2
top2_a
top2_b
top2_b_a
...
Upvotes: 1
Views: 250
Reputation: 71461
You can group your file rows based on the indent depth via recursion:
import re
with open('hierarchy_data.txt') as f:
d = [(j:=(k[0] if (k:=re.findall('^\s+', i)) else ''), i[len(j):].strip('\n')) for i in f]
def full_paths(d, p = []):
if not d:
yield '/'.join(p)
else:
k, r = None, []
for a, b in d:
if not a:
if k is not None:
yield from full_paths(r, p+[k])
k, r = b, []
else:
r.append((a[2:], b))
if k is not None:
yield from full_paths(r, p+[k])
print(list(full_paths(d)))
Output:
['top1/top1_a', 'top1/top1_b', 'top1/top1_c/top1_c_a/top1_c_a_a', 'top1/top1_c/top1_c_a/top1_c_a_b', 'top1/top1_d', 'top2/top2_a', 'top2/top2_b/top2_b_a']
Upvotes: 1