FunPlus
FunPlus

Reputation: 97

Python: How to get a name showing the hierarchy from a given file?

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
...
   
  
In a word, What I want to do is getting a name which shows the hierarchy. For example, top1_c_a should be named as 'top1/top1_c/top_c_a'. Finally, I want to get a list containing these names. What should I do?

Upvotes: 1

Views: 250

Answers (1)

Ajax1234
Ajax1234

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

Related Questions