]> git.armaanb.net Git - lightcards.git/blob - lightcards/parse.py
Add comments to code
[lightcards.git] / lightcards / parse.py
1 #!/usr/bin/env python
2 # Parse markdown table into tuple of lists
3 # Armaan Bhojwani 2021
4
5 import sys
6 from bs4 import BeautifulSoup
7 import markdown
8
9 from .deck import Card
10
11
12 def md2html(file):
13     """Use the markdown module to convert input to HTML"""
14     with open(file, "r", encoding="utf-8") as input_file:
15         return markdown.markdown(input_file.read(), extensions=['tables'])
16
17
18 def parse_html(html):
19     """Use BeautifulSoup to parse the HTML"""
20     def clean_text(inp):
21         return inp.get_text().rstrip()
22
23     def clean_list(inp):
24         for z in inp:
25             if not len(z) == 2:
26                 inp.remove(z)
27         return inp
28
29     soup = BeautifulSoup(html, 'html.parser')
30     outp = []
31
32     for x in soup.find_all("tr"):
33         outp.append(Card([clean_text(y) for y in x.find_all("td")]))
34
35     # Return a tuple of nested lists
36     return ([clean_text(x) for x in soup.find_all("th")],
37             clean_list(outp))
38
39
40 def main(file):
41     return parse_html(md2html(file))
42
43
44 if __name__ == "__main__":
45     print(main(sys.argv[1]))