Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to translate indent title to numbering title in python code

I have a table of content in the form of indent to keep relation like:

- title1
-- title1-1
-- title1-2
--- title1-2-1
--- title1-2-2
- title2
-- title2-1
-- title2-2
- title3
- title4

What I want to is to translate then into form of numbering format like:

1 title1
1.1 title1-1
1.2 title1-2
1.2.1 title1-2-1
1.2.2 title1-2-2
2 title2
2.1title2-1
2.2 title2-2
3 title3
4 title4

I have tried myself, but mostly they were transferred into desired format, but some could not, anyone can provide the perfect code, thanks advanced!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use the replacer callback of re.sub to implement the logic. In that callback use a stack (that is maintained across multiple replacements) to track the chapter numbers of upper "levels".

Code:

import re

def add_numbers(s):
    stack = [0]
    
    def replacer(s):
        indent = len(s.group(0)) - 1
        del stack[indent+1:]
        if indent >= len(stack):
            stack.append(0)
        stack[indent] += 1
        return ".".join(map(str,stack))
        

    return re.sub(r"^-+", replacer, s, flags=re.M)

Here is how you would call it on your example:

message_string = """- title1
-- title1-1
-- title1-2
--- title1-2-1
--- title1-2-2
- title2
-- title2-1
-- title2-2
- title3
- title4"""

res = add_numbers(message_string)
print(res)

This prints:

1 title1
1.1 title1-1
1.2 title1-2
1.2.1 title1-2-1
1.2.2 title1-2-2
2 title2
2.1 title2-1
2.2 title2-2
3 title3
4 title4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading