]> git.armaanb.net Git - lightcards.git/blob - contrib/kvtml2html.py
313a44b04010183e739b464d68172a8a2ab985b2
[lightcards.git] / contrib / kvtml2html.py
1 #!/usr/bin/env python
2 # Converts .kvtml KWordQuiz files to HTML
3
4 import argparse
5 from bs4 import BeautifulSoup
6
7
8 def parse_args():
9     parser = argparse.ArgumentParser(
10         description="Convert KWordQuiz file into Markdown for Lightcards")
11     parser.add_argument("inp", metavar="input file", type=str, nargs=1)
12     parser.add_argument("outp", metavar="output file", type=str, nargs=1)
13     return parser.parse_args()
14
15
16 def main():
17     args = parse_args()
18     with open(args.inp[0], "r", encoding="utf-8") as input_file:
19         soup = BeautifulSoup(input_file, "lxml")
20
21     headers = [x.get_text().split("\n")[1] for x in soup.find_all("identifier")]
22     body = soup.find_all("entry")
23     col1 = [x.find("translation", {"id": "0"}) for x in body]
24     col2 = [x.find("translation", {"id": "1"}) for x in body]
25
26     html = f"<html><table><tr><th>{headers[0]}</th><th>{headers[1]}</th></tr>"
27     for i in range(len(col1)):
28         try:
29             html += f"<html><table><tr><td>{col1[i].get_text().rstrip()}</td>"
30             html += f"<td>{col2[i].get_text().rstrip()}</td></tr>"
31         except:
32             pass
33
34     with open(args.outp[0], "w", encoding="utf-8") as output_file:
35         output_file.write(html)
36
37 if __name__ == "__main__":
38     main()