-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmarkdown2html.py
64 lines (50 loc) · 1.81 KB
/
markdown2html.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/python3
"""
This is a script to convert a Markdown file to HTML.
Usage:
./markdown2html.py [input_file] [output_file]
Arguments:
input_file: the name of the Markdown file to be converted
output_file: the name of the output HTML file
Example:
./markdown2html.py README.md README.html
"""
import argparse
import pathlib
import re
def convert_md_to_html(input_file, output_file):
'''
Converts markdown file to HTML file
'''
# Read the contents of the input file
with open(input_file, encoding='utf-8') as f:
md_content = f.readlines()
html_content = []
for line in md_content:
# Check if the line is a heading
match = re.match(r'(#){1,6} (.*)', line)
if match:
# Get the level of the heading
h_level = len(match.group(1))
# Get the content of the heading
h_content = match.group(2)
# Append the HTML equivalent of the heading
html_content.append(f'<h{h_level}>{h_content}</h{h_level}>\n')
else:
html_content.append(line)
# Write the HTML content to the output file
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(html_content)
if __name__ == '__main__':
# Parse command-line arguments
parser = argparse.ArgumentParser(description='Convert markdown to HTML')
parser.add_argument('input_file', help='path to input markdown file')
parser.add_argument('output_file', help='path to output HTML file')
args = parser.parse_args()
# Check if the input file exists
input_path = pathlib.Path(args.input_file)
if not input_path.is_file():
print(f'Missing {input_path}', file=sys.stderr)
sys.exit(1)
# Convert the markdown file to HTML
convert_md_to_html(args.input_file, args.output_file)