]> git.armaanb.net Git - lightcards.git/blob - lightcards/parse.py
Comment and clean code
[lightcards.git] / lightcards / parse.py
1 # Parse markdown table into tuple of lists
2 # Armaan Bhojwani 2021
3
4 import sys
5 from bs4 import BeautifulSoup
6 import markdown
7
8 from .deck import Card
9
10
11 def md2html(file):
12     """Use the markdown module to convert input to HTML"""
13     try:
14         return markdown.markdown(open(file, "r").read(), extensions=['tables'])
15     except FileNotFoundError:
16         print(f"lightcards: \"{file}\": No such file or directory")
17         exit(1)
18
19
20 def parse_html(html):
21     """Use BeautifulSoup to parse the HTML"""
22     def clean_text(inp):
23         return inp.get_text().rstrip()
24
25     soup = BeautifulSoup(html, 'html.parser')
26     outp = []
27
28     for x in soup.find_all("tr"):
29         outp.append(Card([clean_text(y) for y in x.find_all("td")[:2]]))
30
31     # Return a tuple of nested lists
32     return ([clean_text(x) for x in soup.find_all("th")][:2], outp[1:])
33
34
35 def main(file):
36     return parse_html(md2html(file))
37
38
39 if __name__ == "__main__":
40     print(main(sys.argv[1]))