]> git.armaanb.net Git - lightcards.git/blob - lightcards/parse.py
Add ability to star cards
[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     with open(file, "r", encoding="utf-8") as input_file:
14         return markdown.markdown(input_file.read(), extensions=['tables'])
15
16
17 def parse_html(html):
18     def clean_text(inp):
19         return inp.get_text().rstrip()
20
21     def clean_list(inp):
22         for z in inp:
23             if not len(z) == 2:
24                 inp.remove(z)
25         return inp
26
27     soup = BeautifulSoup(html, 'html.parser')
28     outp = []
29
30     for x in soup.find_all("tr"):
31         outp.append(Card([clean_text(y) for y in x.find_all("td")]))
32
33     return ([clean_text(x) for x in soup.find_all("th")],
34             clean_list(outp))
35
36
37 def main(file):
38     return parse_html(md2html(file))
39
40
41 if __name__ == "__main__":
42     print(main(sys.argv[1]))