-
Notifications
You must be signed in to change notification settings - Fork 0
/
translator.py
105 lines (76 loc) · 2.69 KB
/
translator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import argparse
from requests_html import HTMLSession
from prettytable import PrettyTable
available_langs = {
"nl": "Dutch",
"en": "English",
"fr": "French",
"de": "German",
"es": "Spanish",
"it": "Italian",
"pt": "Portugese",
"da": "Danish",
"sv": "Swedish"
}
description = "Translate a word (vertalen.nu).\
Available languages: \
nl (Nederlands)\
en (English)\
fr (Français)\
de (Deutsch)\
es (Español)\
it (Italiano)\
pt (Português)\
da (Dansk)\
sv (Svenska)"
def parse_arguments():
parser = argparse.ArgumentParser(
description=description)
parser.add_argument("word", type=str,
help="Word that needs to be translated.")
parser.add_argument("source", type=str,
help="Soure language.")
parser.add_argument("target", type=str,
help="Target language.")
args = parser.parse_args()
if args.source == args.target:
print("\nCannot use source language as target language.\n")
exit()
if args.source not in available_langs.keys() or args.target not in available_langs.keys():
print("\nLanguage not supported.\n")
parser.print_help()
exit()
return args
def get_result(payload):
session = HTMLSession()
r = session.get("https://www.vertalen.nu/vertaal?", params=payload)
synonyms = r.html.find(".result-item-source")
translations = r.html.find(".result-item-target")
if not translations:
print("No translations found.")
exit()
return {"synonyms": [word.text for word in synonyms],
"translations": [word.text for word in translations]}
def setup_table(result, src, target):
table = PrettyTable()
source_header = available_langs[src] + " (" + src + ")"
target_header = available_langs[target] + " (" + target + ")"
table.field_names = [source_header,
target_header]
table.align[source_header] = "l"
table.align[target_header] = "l"
for i, r in enumerate(result["synonyms"]):
table.add_row([r, result["translations"][i]])
table.add_row(["\n", "\n"])
return table
def main():
args = parse_arguments()
src = args.source
target = args.target
payload = {"vertaal": args.word, "van": src, "naar": target}
result = get_result(payload)
print()
print(setup_table(result, src, target))
print()
if __name__ == "__main__":
main()