You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.6KB

  1. #!/usr/bin/python3
  2. import requests
  3. import sys
  4. import textwrap
  5. def connection_error():
  6. print("Could not contact wikipedia servers.")
  7. sys.exit(1)
  8. def page_search(string):
  9. params = {
  10. 'q' : string,
  11. 'limit' : 1
  12. }
  13. try:
  14. return requests.get('https://en.wikipedia.org/w/rest.php/v1/search/page', params).json()['pages']
  15. except ConnectionError:
  16. connection_error()
  17. def get_page_with_summary(title):
  18. try:
  19. return requests.get('https://en.wikipedia.org/api/rest_v1/page/summary/' + title).json()
  20. except ConnectionError:
  21. connection_error()
  22. def get_page_links(title):
  23. params = {
  24. 'action' : 'query',
  25. 'titles' : title,
  26. 'prop' : 'links',
  27. 'format' : 'json'
  28. }
  29. try:
  30. return list(requests.get('https://en.wikipedia.org/w/api.php', params).json()['query']['pages'].values())[0]['links']
  31. except ConnectionError:
  32. connection_error()
  33. def main():
  34. if not sys.argv[1:]:
  35. print("Usage: wikipedia <list of search terms>")
  36. sys.exit(1)
  37. else:
  38. result = page_search(' '.join(sys.argv[1:]))
  39. if result:
  40. page = get_page_with_summary(result[0]['title'])
  41. if page['type'] == 'disambiguation':
  42. print('Ambiguous result, please clarify:\n ' + '\n '.join([link['title'] for link in get_page_links(page['title'])]))
  43. else:
  44. print(page['title'] + ':\n\n' + textwrap.fill(page['extract'], width=80))
  45. else:
  46. print('No result found.')
  47. sys.exit(1)
  48. if __name__ == '__main__':
  49. main()