prev next 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Loading a List from the Internet

I have an even longer list of animals on the internet, at http://davidbau.com/data/animals.

If your computer happens to be connected to the internet, you can load this data in python using a function called "urllib.urlopen". (URLs are what web addresses are called, so urllib stands for "URL library," and urlopen means "open a URL.")

The code looks like this:


import urllib

animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)

What this means is:

import urllib
Import the library called "urllib" to use.
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
Open up the address http://davidbau.com/data/animals
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
Read the whole webpage into a big string.
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
Split the string into a list of words.
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
Call the whole list "animals".
secret = random.choice(animals)
Choose a random one and call it "secret."

You can use urllib to load up more data than you could ever type in yourself.