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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
#!/usr/bin/env python3
# A script to fetch information from https://dict.cc/ and display it in the terminal
# Depends on: python3, beautifulsoup4, tabulate, pynput, requests
# By David Penkowoj, 2021/01/11
# https://stackoverflow.com/questions/65328213/how-to-prevent-certain-certain-keys-from-sending-input-in-python
import sys
import requests
from pynput import keyboard
from tabulate import tabulate
from bs4 import BeautifulSoup
index = 0
entry = "Allgemein"
dictionary = {}
found_rows = []
keys = []
def get_file():
file = "/tmp/$1.dictcc"
link = "http://www.dict.cc/?s=" + sys.argv[1]
agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"
headers = { "User-Agent": agent }
return requests.get(link, headers = headers, allow_redirects=True)
def setup():
file = get_file()
parsed = BeautifulSoup(file.content, features = "html5lib")
found_table = parsed.body.find("table", attrs = {"cellspacing": "1"})
global found_rows
found_rows = found_table.find_all("tr")
found_rows[0].decompose()
print(found_rows[1].text + "\n")
found_rows[1].decompose()
global dictionary
dictionary = {entry: []}
def add_translation(items):
global entry
global dictionary
translation = [];
for item in items:
translation.append(item.text)
if len(translation) == 0:
continue
dictionary[entry].append(translation)
def stop():
print(chr(27) + "[2J")
print("Exit")
sys.exit(0);
def showpage(key):
global index
if not safe_index(index):
stop()
print(chr(27) + "[2J")
print(tabulate(dictionary[key], [key.ljust(60, " "), "-".ljust(60, " ")], tablefmt="fancy_grid"))
print("\n[j] next, [k] previous, [q] quit")
def safe_index(i):
if i >= 0 and i < len(keys):
return True
return False
def on_press(key):
global index
if "char" in dir(key):
if key.char == 'q' or not safe_index(index):
stop()
if key.char == 'j':
index=(index + 1)
if key.char == 'k':
index=(index - 1)
showpage(keys[index])
def main():
global keys
global found_rows
for row in found_rows:
found_items = row.find_all("td", attrs = {"dir": "ltr"})
if len(found_items) == 0:
found_items = row.find_all("td", attrs = {"colspan": "4"})
if len(found_items) == 1:
global entry
global dictionary
entry = found_items[0].text
dictionary[entry] = []
continue
else:
continue
#dfn div
add_translation(found_items)
keys = list(dictionary)
showpage(keys[index])
with keyboard.Listener(suppress=True, on_press=on_press) as listener:
listener.join()
setup()
main()
|