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
|
#!/usr/bin/env python
import shlex
import optparse
import sys
import wikipedia
from functools import partial
version = "0.1.7"
def stringify(o):
if isinstance(o, list):
output = []
for i, item in enumerate(o, 1):
output.append("%s: %s" % (i, item))
return ' %s' % ', '.join(output)
else:
return o;
def display(o):
print (stringify(o))
def search(topic, index):
results = wikipedia.search(topic)
if len(results) == 1:
display(wikipedia.summary(results[0]))
else:
if index is not None:
try:
display(wikipedia.summary(results[index]))
except IndexError:
print ("index out of range, options are: [%s]" % stringify(results))
else:
display(results)
def url(topic, index):
try:
page = wikipedia.page(topic)
except wikipedia.exceptions.DisambiguationError as e:
if index is not None:
try:
display(wikipedia.page(e.options[index]).url)
except IndexError:
print ("index out of range, options are: [%s]" % stringify(e.options))
else:
display(e.options)
else:
display(page.url)
def summary(topic, index):
try:
display(wikipedia.summary(topic))
except wikipedia.exceptions.DisambiguationError as e:
if index is not None:
try:
display(wikipedia.summary(e.options[index]))
except IndexError:
print ("index out of range, options are: [%s]" % stringify(e.options))
else:
display(e.options)
except wikipedia.exceptions.PageError as e:
print ("No wikipedia results found for %s" %topic)
def parse_args():
args = sys.argv[1:]
if not args:
args = sys.stdin.read().split()
parser = optparse.OptionParser(usage="!wiki <topic> [index] [--search|--url]")
parser.add_option("--search", action="store_true")
parser.add_option("--url", action="store_true")
parser.add_option("-v", "--version", action="store_true")
return parser.parse_args(args)
def main():
options, args = parse_args()
if options.version:
print (version)
sys.exit(0)
if args:
topic = args.pop(0)
while len(args) > 0 and not(isinstance(args[0], (int,long))):
topic += " " + args.pop(0)
index = int(args.pop(0)) if args else None
if options.search:
search(topic, index)
elif options.url:
url(topic, index)
else:
summary(topic, index)
if __name__ == "__main__":
main()
|