Created
August 14, 2016 22:19
-
-
Save mbasaglia/5d98aa5936c787a67d578dabad2568f3 to your computer and use it in GitHub Desktop.
Selects a random pony name from the mlp wiki.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
import json | |
import random | |
class PonyList(object): | |
api_url = "http://mlp.wikia.com/api.php" | |
query_common = { | |
"action": "query", | |
"list": "categorymembers", | |
"format": "json", | |
"cmlimit": "300", | |
} | |
ponies = [] | |
categories = [] | |
def __init__(self, *categories): | |
self.categories = categories | |
def __iter__(self): | |
if self.ponies: | |
for pony in self.ponies: | |
yield pony | |
for category in self.categories: | |
for pony in self.generate_ponies(category): | |
yield pony | |
def load(self): | |
self.ponies = [] | |
for category in self.categories: | |
for pony in self.generate_ponies(category): | |
pass | |
def generate_ponies(self, category): | |
query_continue = {} | |
while True: | |
query = self.query_common.copy() | |
query["cmtitle"] = "Category:" + category.lower().replace(' ', '_') | |
query.update(query_continue) | |
url = self.api_url + '?' + urllib.urlencode(query) | |
response = json.load(urllib.urlopen(url)) | |
for page in response["query"]["categorymembers"]: | |
pony = page["title"] | |
if "/" not in pony and ":" not in pony: | |
self.ponies.append(pony) | |
yield pony | |
if "query-continue" in response: | |
query_continue = response["query-continue"]["categorymembers"] | |
else: | |
break | |
pony_list = PonyList("Alicorn ponies", "Unicorn ponies", "Pegasus ponies", "Earth ponies") | |
pony_list.load() | |
print random.choice(pony_list.ponies) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment