| 1 |
import json |
| 2 |
|
| 3 |
try: |
| 4 |
from urllib.request import Request, urlopen |
| 5 |
except ImportError: |
| 6 |
from urllib2 import Request, urlopen |
| 7 |
|
| 8 |
import collections |
| 9 |
import operator |
| 10 |
import sys |
| 11 |
|
| 12 |
WIKIPEDIA_ARTICLE_API_URL = "https://en.wikipedia.org/w/api.php?action=query&titles=Spoon&prop=revisions&rvprop=content&format=json" |
| 13 |
|
| 14 |
|
| 15 |
def download(): |
| 16 |
headers = {"User-Agent": "pyinstrument demo script"} |
| 17 |
req = Request(WIKIPEDIA_ARTICLE_API_URL, headers=headers) |
| 18 |
return urlopen(req).read() |
| 19 |
|
| 20 |
|
| 21 |
def parse(json_data): |
| 22 |
return json.loads(json_data) |
| 23 |
|
| 24 |
|
| 25 |
def most_common_words(page): |
| 26 |
word_occurences = collections.defaultdict(int) |
| 27 |
|
| 28 |
for revision in page["revisions"]: |
| 29 |
article = revision["*"] |
| 30 |
|
| 31 |
for word in article.split(): |
| 32 |
if len(word) < 2: |
| 33 |
continue |
| 34 |
word_occurences[word] += 1 |
| 35 |
|
| 36 |
word_list = sorted(word_occurences.items(), key=operator.itemgetter(1), reverse=True) |
| 37 |
|
| 38 |
return word_list[0:5] |
| 39 |
|
| 40 |
|
| 41 |
def main(): |
| 42 |
data = parse(download()) |
| 43 |
page = list(data["query"]["pages"].values())[0] |
| 44 |
|
| 45 |
sys.stderr.write("This most common words were %s\n" % most_common_words(page)) |
| 46 |
|
| 47 |
|
| 48 |
if __name__ == "__main__": |
| 49 |
main() |