]> git.armaanb.net Git - lightcards.git/blob - lightcards/parse.py
Add menu keybindings to config
[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         raise Exception(
17             f'lightcards: "{file}": No such file or directory'
18         ) from None
19
20
21 def parse_html(html):
22     """Use BeautifulSoup to parse the HTML"""
23
24     def clean_text(inp):
25         return inp.get_text().rstrip()
26
27     soup = BeautifulSoup(html, "html.parser").find("table")
28     outp = []
29
30     try:
31         for x in soup.find_all("tr"):
32             outp.append(Card(tuple([clean_text(y) for y in x.find_all("td")])))
33     except AttributeError:
34         raise Exception("lightcards: No table found") from None
35
36     ths = soup.find_all("th")
37     if len(ths) != 2:
38         raise Exception("lightcards: Headings malformed")
39
40     # Return a tuple of nested lists
41     return ([clean_text(x) for x in ths], outp[1:])
42
43
44 def main(file):
45     return parse_html(md2html(file))
46
47
48 if __name__ == "__main__":
49     print(main(sys.argv[1]))