56 lines
1.6 KiB
Plaintext
56 lines
1.6 KiB
Plaintext
|
#!/usr/bin/python3
|
||
|
import requests
|
||
|
import sys
|
||
|
import textwrap
|
||
|
|
||
|
def connection_error():
|
||
|
print("Could not contact wikipedia servers.")
|
||
|
sys.exit(1)
|
||
|
|
||
|
def page_search(string):
|
||
|
params = {
|
||
|
'q' : string,
|
||
|
'limit' : 1
|
||
|
}
|
||
|
try:
|
||
|
return requests.get('https://en.wikipedia.org/w/rest.php/v1/search/page', params).json()['pages']
|
||
|
except ConnectionError:
|
||
|
connection_error()
|
||
|
|
||
|
def get_page_with_summary(title):
|
||
|
try:
|
||
|
return requests.get('https://en.wikipedia.org/api/rest_v1/page/summary/' + title).json()
|
||
|
except ConnectionError:
|
||
|
connection_error()
|
||
|
|
||
|
def get_page_links(title):
|
||
|
params = {
|
||
|
'action' : 'query',
|
||
|
'titles' : title,
|
||
|
'prop' : 'links',
|
||
|
'format' : 'json'
|
||
|
}
|
||
|
try:
|
||
|
return list(requests.get('https://en.wikipedia.org/w/api.php', params).json()['query']['pages'].values())[0]['links']
|
||
|
except ConnectionError:
|
||
|
connection_error()
|
||
|
|
||
|
def main():
|
||
|
if not sys.argv[1:]:
|
||
|
print("Usage: wikipedia <list of search terms>")
|
||
|
sys.exit(1)
|
||
|
else:
|
||
|
result = page_search(' '.join(sys.argv[1:]))
|
||
|
if result:
|
||
|
page = get_page_with_summary(result[0]['title'])
|
||
|
if page['type'] == 'disambiguation':
|
||
|
print('Ambiguous result, please clarify:\n ' + '\n '.join([link['title'] for link in get_page_links(page['title'])]))
|
||
|
else:
|
||
|
print(page['title'] + ':\n\n' + textwrap.fill(page['extract'], width=80))
|
||
|
else:
|
||
|
print('No result found.')
|
||
|
sys.exit(1)
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
main()
|