I wrote a Python script to format plain text to markdown title.
for example, modify multiple lines
['1 Introduction\n',
'Part I: Applied Math and Machine Learning Basics\n',
'2 Linear Algebra\n',
'3 Probability and Information Theory\n',
'10 Sequence Modeling: Recurrent and Recursive Nets\n',
'11 Practical Methodology']
to
['# chapter1: Introduction\n',
'Part I: Applied Math and Machine Learning Basics\n',
'# chapter2: Linear Algebra\n',
'# chapter3: Probability and Information Theory\n',
'# chapter10: Sequence Modeling: Recurrent and Recursive Nets\n',
'# chapter11: Practical Methodology']
each chapter title in original file starts with only a number, modify them from 1 to "# chapter 1:", namely, insert "# chapter " before the number, append a colon ":" behind the number; finally write the new toc to a file.
here is the code
import re
# f_name = 'data_multi_lines_3.md'
f_name = 'data_multi_lines.txt'
with open(f_name) as f:
line_list = f.readlines()
res_list = []
for line in line_list:
res_list.append(re.sub(r'^(\d{1,2})( +.*?)', r'# chapter\1:\2', line))
with open('your_file.md', 'w') as f:
for item in res_list:
f.write("%s" % item)
Is there a better approach to do this?
I guess I should be concerned about the for loop although I have no idea how to improve that.