3
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

iterator

There is no need for the intermediate list, just iterate over the text file line per line, and write the parsed line to the output file

variable name

f_name those 3 characters will not make writing or executing the code any slower, but writing it in full can help you understand the code later one

re.compile

You can compile the regular expression

For extra points, you can also name the groups:

re_pattern_chapter = re.compile(r"^(?P<chapter>\d{1,2})(?P<text> +.*?)")
re_pattern_out = r"# chapter(?P=chapter):(?P=text)"

import re

file_name_in = "data_multi_lines.txt"
file_name_out = "your_file.md"

re_pattern_chapter = re.compile(r"^(?P<chapter>\d{1,2})(?P<text> +.*?)")
re_pattern_out = r"# chapter(?P=chapter):(?P=text)"

with open(file_name_in, "r") as file_in, open(file_name_out, "w") as file_out:
    for line in file_name_in:
        line_parsed = re_pattern_chapter.sub(re_pattern_out, line)
        file_out.write(line_parsed)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.