Instantly share code, notes, and snippets.

Embed
What would you like to do?
DIS script
#!/usr/bin/env python3
"""DIS slovarček api
Usage:
dis [options] [QUERY [QUERY ...]]
Options:
-h --help Show this screen.
--version Show version.
"""
from urllib.request import urlopen
from urllib.parse import urlencode
from pyquery import PyQuery as pq
from docopt import docopt
SEARCH_URL = 'http://dis-slovarcek.ijs.si/search?{}'
LINE_QUERY = '{}:\n'
LINE_RESULT = ' * {} -> {}\n'
def search(query):
print(LINE_QUERY.format(query), end='')
results = pq(url=SEARCH_URL.format(urlencode({ 'text': query })),
opener=lambda url, **kw: urlopen(url).read().decode('utf8'))
for acc in results('div#all-search-results div.accordion'):
acc = pq(acc)
left = acc('div.search-result-left p').text()
right = acc('div.search-result-right p').text()
print(LINE_RESULT.format(left, right), end='')
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1')
queries = arguments.get('QUERY')
if queries:
search(' '.join(queries))
else:
import subprocess
p = subprocess.Popen(['xclip', '-o'], stdout=subprocess.PIPE)
out, err = p.communicate()
if not err:
search(out.decode('utf8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment