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!
>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