20 May 2010

OpenDataBC: Extracting Data from A4CA PDFs

In this OpenDataBC series of posts, I describe how to use some of the data that is being made available by the government of British Columbia on http://data.gov.bc.ca and related web sites. In the first article of this series, I described how to write a script to scrape catalog data from web pages. In the second article I described how to write a program to transform the data. In this article, I describe how to convert a PDF document into useable data.

As part of the Apps for Climate Action Contest, the Province of BC released over 500 datasets in the Climate Action Data Catalogue. It's an impressive amount of data pulled from an array of sources both within BC and elsewhere.

In an ideal “open data” world, all of that data would be in an easily machine readable format that we could use to write programs directly. While that would be great, the reality today is a bit different. Much of the data that is made publicly available these days is in formats that are harder to use. For example, some of the data in the Climate Change Data Catalogue was released in PDF format. PDF is a proprietary format, meaning the format is controlled exclusively by one party, in this case the Adobe corporation.

An interesting fact is that it takes extra effort to get data from its raw form into PDF format. In other words, to publish data in an open format rather than in PDF format actually saves time, effort and money – up front. However, PDF became well established in the pre-open world, so a lot of data is already published using it. To switch existing software to publish in an open format might take time. As a result, at least temporarily, we need to find ways to get at the data in the PDF files.

In this post I describe how to do that. Looking through some of the available datasets in the catalogue, one that I find interesting is “Transit Ridership in Metro Vancouver”. The data is produced by Translink and is in a PDF format and looks like this:



What I am interested in is the number of passenger trips by year for the past few years. I am going to leave out the Seabus and the West Coast Express as I am mostly interested in the buses and the Skytrain.

What I would like is a dataset, in a CSV file. The way this program will work is essentially as follows:

  • read the data from the source database
  • extract the data from the PDF file into a list in memory
  • write the list in memory out to a CSV file

Prerequisites
The following code requires the Python programming language, which comes pre-installed on all Linux and modern Mac machines and can be easily installed on Windows.

The Code
The first thing we need to do is to read the PDF file into memory. The simple way to do that in Python is to use the urllib2 library and read the entire PDF from the original web site. Tying the script to the actual location of the file means we don't manually store the orginal file anywhere. If the City of Vancouver decided to move the URL we would have to adjust our code, but we're probably only going to run this code once so it's not a big deal. To read the PDF file into a memory variable we do this:

import urllib2 
    url = 'http://www.metrovancouver.org/about/publications/Publications/KeyFacts-TransitRidership1989-2008.pdf'
    pdf = urllib2.urlopen(url).read() 

Now that we have the PDF file in memory, I want to parse the PDF file and turn it into raw text. To do this I use a free open source Python library called pdfminer. I have created a function called pdf_2_text for this purpose. Here's the function:

def pdf_to_text(data): 
    from pdfminer.pdfinterp import PDFResourceManager, process_pdf 
    from pdfminer.pdfdevice import PDFDevice 
    from pdfminer.converter import TextConverter 
    from pdfminer.layout import LAParams 

    import StringIO 
    fp = StringIO.StringIO() 
    fp.write(data) 
    fp.seek(0) 
    outfp = StringIO.StringIO() 
    
    rsrcmgr = PDFResourceManager() 
    device = TextConverter(rsrcmgr, outfp, laparams=LAParams()) 
    process_pdf(rsrcmgr, device, fp) 
    device.close() 
    
    t = outfp.getvalue() 
    outfp.close() 
    fp.close() 
    return t

The pdf_to_text function starts by importing the components required to do the conversion. The pdfminer library provides a lot of functionality. In this example we are using a small fraction of its functionality to do what we need, which is to get at the content in the PDF. The main function that actually does the work is called process_pdf. It takes a PDFResourceManager object, a TextConverter object and a file object as parameters so the code before that call is setting up those parameters properly. I use a StringIO object rather than just passing the urllib2 object in because the PDF converter needs to use the seek method for random access which is not supported in urllib2. To gain this ability I put the data into a StringIO object, which supports seek.

When the pdf_to_text function is called with the contents of a PDF file it returns a string containing lines of text with each line containing one of the elements (numbers or labels) of the PDF file. Here's what it looks like on my system:



Now that we have the data in text format, we want to pull out the numbers that we are interested in. I am interested in the labels on the left, which start on line 6, the first numeric column (BUS), which starts on line 75 and the second numeric column (SKYTRAIN), which starts on line 144.

To start the process of extracting rows of data from the text file, I first split lines of the text file into a list like this:

lines = text.splitlines() 

Then I create a simple function called grab_one_row which besides having a very clever name, knows the relative placement of the three columns, and pulls one whole row at a time from the text file and returns it as a tuple. Here is the function:

def grab_one_row(lines,n): 
    return (lines[n],long(lines[n+69].replace(',','')),long(lines[n+138].replace(',',''))) 

Armed with that function, I can now collect most of the rows I am interested in with a simple generator line:

rows = [grab_one_row(lines,i) for i in range(6,26)] 

In the original PDF, the data for 2008 is placed further down the page so the last line needs to be added with a separate line of code like this:

rows.append(grab_one_row(lines,39)) 

now the rows array contains all of the data we are interested in, in an array that we can easily deal with. We just need to write them out to a CSV file to complete our work. To do that I created the rows_to_csv function. Here it is:

def rows_to_csv(rows,filename): 
    # write the clean data out to a file 
    import csv 
    f = open(filename,'w') 
    writer = csv.writer(f,delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC) 
    writer.writerow(rows[0]) 
    for row in rows[1:]: 
        writer.writerow((row[0],long(row[1].replace(',','')),long(row[2].replace(',','')))) 

I wanted the resulting CSV file to have numbers rather than strings containing numbers for the numeric values. The last line of this function strips out the commas that were in the numbers in the PDF file and then converts the text to a long integer to be written the CSV file.

The resulting CSV file now looks like this:



This result is a lot easier to deal with than the original PDF file. Arguably, a small file such as this could also be converted with Open Office Spreadsheet by cutting from the PDF and pasting to the spreadsheet. The nice thing about doing this as a script as above is that we can use this same technique for very large PDF files that would be too onerous to do manually.

Here is the entire program with all of the code together at once:

def pdf_to_text(data): 
    from pdfminer.pdfinterp import PDFResourceManager, process_pdf 
    from pdfminer.pdfdevice import PDFDevice 
    from pdfminer.converter import TextConverter 
    from pdfminer.layout import LAParams 

    import StringIO 
    fp = StringIO.StringIO() 
    fp.write(data) 
    fp.seek(0) 
    outfp = StringIO.StringIO() 
    
    rsrcmgr = PDFResourceManager() 
    device = TextConverter(rsrcmgr, outfp, laparams=LAParams()) 
    process_pdf(rsrcmgr, device, fp) 
    device.close() 
    
    t = outfp.getvalue() 
    outfp.close() 
    fp.close() 
    return t 
    
def grab_one_row(lines,n): 
    return (lines[n],lines[n+69],lines[n+138]) 

def rows_to_csv(rows,filename): 
    # write the clean data out to a file 
    import csv 
    f = open(filename,'w') 
    writer = csv.writer(f,delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC) 
    writer.writerow(rows[0]) 
    for row in rows[1:]: 
        writer.writerow((row[0],long(row[1].replace(',','')),long(row[2].replace(',','')))) 

def run(): 
    import urllib2 
    url         = 'http://www.metrovancouver.org/about/publications/Publications/KeyFacts-TransitRidership1989-2008.pdf' 
    outfilename = 'translink_bus_skytrain_trips_1989_2008.csv' 
    
    pdf = urllib2.urlopen(url).read() 
    text = pdf_to_text(pdf) 
    
    lines = text.splitlines() 
    rows = [grab_one_row(lines,i) for i in range(6,26)] 
    rows.append(grab_one_row(lines,39)) 

    rows_to_csv(rows,outfilename) 
    
if __name__ == '__main__': 
    run() 

and you can find the resulting CSV file here.

Once again, Python comes through for us. Clearly it's not as easy to convert a PDF file as it is to rip a table out of an HTML file, but being possible at all makes it something we can work with. And part of the beauty of “Open” is that now that I have done it, others don't have to. And I in turn will benefit from other contributors to the open ecosystem. If we all do a bit, it's an “everyone wins” scenario.

17 May 2010

Facebook Steps Out of the Way

Like most people, I was a bit surprized with Facebook's recent changes with regard to privacy.  I don't think they have done anything wrong, but as a user I allowed myself to be lulled into a false sense of security.  Like most people, I believed that they wouldn't mess with the privacy settings of my account much, allowing me to control who got to see the personal information I put on Facebook on my terms.  I had agreed to their user agreement which stated they could change the terms at any time, but I didn't really pay attention to that fine print.

When they made the more recent change to allow my friends graph and my content to be harvested I realized something.  Not that Facebook is evil or bad, but that they offer a service that I thought was one thing, but it is something else.  I thought it was a way for me to connect with my friends and share my data with them, but actually it is a way for Facebook to profit from our personal data.  Or, as Tim Spalding so eloquently put it, "Why do free social networks tilt inevitably toward user exploitation? Because you're not their customer, you're their product."

For me it's not a big deal that my Facebook content is now available to anyone, I don't store anything particularly private there anyway.  But now, my behaviour has changed and I find myself using it even less than I did before.  Not so much because of the loss of control over my data or the fact that they didn't give me a cut, but because this is a company that is volatile with respect to its user policies.  Frankly, I just don't want to put in the time required to keep up with their changes.  So, I take my privacy into my own hands and limit what I place on Facebook.

On the other hand, I find the recent changes to Facebook pretty exciting.  I think an awesome opportunity has opened up now for a service to emerge that allows people to connect with their friends and at the same time protects their privacy.  400 million facebook users sharing information is a testament to the fact that people want to connect online.  The recent outcries and Facebook account deletions point to the fact that people also value privacy...i.e., there is clearly a market for connecting AND protecting privacy.

Facebook doesn't offer that service, but until now people were not sure if they did or they didn't.  And that ambiguity prevented other firms from offering that service because competing with Facebook was just a non-starter.  Now, thanks to Facebook's recent changes, it's clear.  They don't.

And in that gap between what people want and what is available, lies opportunity.

It's now clear, Facebook is not in the privacy business.  By stepping out of the way they make room for others that want to offer privacy as a key value proposition.

Personally, I would like to see a new type of social platform emerge.  Something taking ideas from status.net and webfinger and Diaspora.  I want a distributed social platform that I can host with any hosting provider that would allow me to connect with my friends. The difference is, I own it.  So long as my friends and I  have this system installed somewhere, our systems would talk to each other seamlessly.

This way we would not be dependent or at the mercy of any one vendor or their privacy policy changes.  We would be able to move our accounts to another host of our choosing, anytime we want, and we would be able to lock down or even delete data any time.

The software would be free and open source as well.  If anyone wanted to add some functionality or just contribute, that would be possible too.  Think self-hosted WordPress, but with social networking instead of blogging.

Rather than one massive "walled garden" users would each have their own garden in a community with other garden owners.  They would be able to share their data with whomever they choose.

I am grateful to Facebook and everything it has done to connect people.  It's truly an awesome service.

Ultimately though, it IS my data.  And I still want to share it on my terms.

11 May 2010

Innovators Isolation

One of the things that all innovators face at some level is a sense of isolation. By definition innovators are working on things that have never been worked on before. And they make up only about 2.5% of the population. If they participate in a specialized industry, it's pretty unlikely they'll get to work with other innovators in their field, never mind find someone who understands what it is they're so passionate about.

About four years ago I made a decision to attend four conferences per year. I consider it part of my ongoing professional development in two ways:

  1. Training - there are no formal training courses available for the skills I need for my work. I read any books that are available. Conference workshops and sessions provide me with the most current and relevant information about what other innovators are doing in my field.
  2. Connecting - when I attend a conference, I consciously choose to meet and connect with other attendees and presenters. I often get to connect with other inventors of some of the most exciting new technologies. It's typical to find folks exchanging ideas, talking about what we've actually done, what worked, what didn't work and we're thinking about for the future.  There are people who talk and there are people who ship. These people ship.

Next week I will attend Google I/O and later this year I will attend OSCON and possibly FOWA. Although I don't expect to find a workshop covering specifically what I am currently up to – such as privacy enhancing distributed enterprise service topologies or dataset forking technologies or probabilistic data linkage techniques - at these conferences, I do expect to find lots of people interested in the cutting edge of whatever it is they're passionate about.

I expect to find people who are daring to think differently. I will share my crazy ideas. I will hear other folks’ crazy ideas. I expect we'll have thoughts about each other's crazy ideas and I expect that after all that, we will acknowledge some of the ideas as crazy or just dumb. And some will seem not quite as crazy as they did before.

But more importantly, we will get the sense that we're not the only ones with crazy ideas, and we're not the only ones that have no idea what's on TV anymore, because we are working on something that we think is cool and could possibly even change the world.

06 May 2010

freedom debt and the decline of lock-in




Early adopters are starting to notice there's a cost to cool when it's supplied by a single vendor.  At first it's all fun and games.  Then you realize that you no longer own your music collection, you no longer own your social network, and you no longer own your data.

Time after time we see organizations start out challenging the status quo, getting huge, abusing their user base, breaking trust, declining, and finally becoming the legacy they fought against.  Facebook innovated past MySpace, Microsoft innovated past the IBM mainframe and Apple innovated past the IBM PC.  Years later, Facebook's commoditization of users and user content,  Microsoft's crushing domination of the PC market, and Apple's rigid control over anything that comes into contact with its products, including the internet, are all examples of lock-in in action.

They all start with great innovations and intentions but eventually the temptation to use lock-in as a strategy becomes too much to resist.  

It's the classic Innovators Dilemma.  

To amass a huge user base, organizations start out providing something of value or at least perceived value.  That's what gets people to join up.  The more compelling and universally recognized the value is, the more users.  Having first mover's advantage is great here because it means there is no competition.

Once people have joined, there's a need to retain them as customers.  

Option one is continuing to provide value over and above what their competitors offer.  Now that their competitors know what they're up to, it's only a matter of time before the innovation is imitated and possibly exceeded.  Continuing to innovate (taking risks) after they've already captured an audience can be difficult and something that doesn't come natural to large organizations.   

Option two, which is what most organizations default to, is the strategy of intentional 'lock-in'.  Lock-in is the practice of structuring the customer relationship so that it's difficult or impossible for users to switch to another vendor.  Such as holding user data hostage so that it can be entered but not retrieved, or preventing people from moving their purchased music to another platform.  Creating a walled garden environment, so if you want to play, you have to play within the walls, and leaving means leaving your toys behind.  These are just a few of the tactics used to discourage people from using their freedom of choice.  

Notice there's a common thread in option two: none of these tactics are in your best interest.  They are in the best interest of the organization.  

Jim Zemlin said it well at LinuxWorld a couple of years ago.  He likened using a certain well known set of products as volunteering to go to jail.   He pointed out that the  Jail looked a lot like a 4 star hotel room with video on demand, a great view, was clean and neat, and that most of us would find to be rather luxurious... but it's still a jail.

Freedom Debt
By offering you something shiny now, organizations get you to give up a bit of your freedom in the future.  "Take this shiny phone.  It's free", they say. "Don't concern yourself with where your data is stored; we'll take care of it."  

Right.

As we continue to wake up to what lock-in means and to become aware that what we are doing when we choose products and vendors that lock us in is essentially borrowing freedom from the future, I think we'll start to make different choices. 

The New Organization
The trends around open source, open data, open government, open protocols, open API's and open communications, indicate that more and more organizations are recognizing that people are aware of the consequence of giving up their freedom.  These organizational models point to lock-in as something to avoid, and use it as a lever to distinguish themselves from the legacy organizational models they disrupt.  

This not only makes those organizations more competitive, it also means their goals are more aligned with ours, and gives us something more valuable for the dollars or attention we give in return.  

And the big upside for them is that openness and our knowing we can leave at any time builds a kind of trust and loyalty that the old model can't hope to compete with.

02 May 2010

OpenDataBC #2: The A4CA Data Catalogue Transformer

In the OpenDataBC series of posts I describe how to use some of the data that is being made available by the government of British Columbia on http://data.gov.bc.ca and related web sites.  My goal is to encourage people that might not otherwise consider interacting directly with data, to give it a try and see for themselves that it's easy, and maybe even fun.  :-)

Three weeks ago I sat down to have a closer look at the datasets that were released as part of the Province of BC's Apps 4 Climate Action (A4CA) contest.  I am very excited about the prospect of open data in BC and wanted to see what was available that might be interesting to use for various projects.  When I started to look through the datasets, I realized I was going to need to download it into either a spreadsheet or database to be able to really look at what was available.

In the previous article of this series, I described how to write a script to scrape the catalog data from the web page that contains it.  In this article I describe how to write a program to transform the data.

The goal of this program is to read the live catalog from the A4CA site and make it available in a useable form.  The program will do some data cleaning and write the data out to a file that can be read by a spreadsheet or database program.  I have decided to output the catalog data in a comma delimited form otherwise known as a csv file.

While writing the last article, I noticed that when the data was downloaded the data had some broken lines, extra spaces and some of the data was encoded with HTML encoding (for example: '≥').  I want to be able to view the data in a plain text editor and in a simple spreadsheet program.  This means cleaning all of these extra lines and codes out so the data is easy to work with and understand during analysis.

The way this program will work is basically as follows:
  • read the data from the catalog page
  • clean the data
  • write the clean data out to a csv file

Prerequisites
The following code requires the Python programming language, which comes pre-installed on all Linux and modern Mac machines and can be easily installed on Windows.

The Code
One of the first things we are going to need to do is grab the catalog data.  I saved my code from the last article in a module called read_a4ca_catalog. To make that module available I just import it.  We are also going to need a few other modules in our program so I import those at the same time.  The string module will help us when we want to clean the data.  We'll use the csv module when we want to write our output to a file.

import read_a4ca_catalog
import string
import csv

Now that we have all of the basic modules loaded we are set to start coding.

Reading the dataset is ridiculously easy now that we have a module specifically written to do that.  It's a one-liner that uses our module from last time:

raw_data = read_a4ca_catalog.read_a4ca_catalog()

Now we have our data in a list variable and we need to clean it.  For that we're going to go through the data row by row, cleaning each row and placing it into a new array called clean_data.

clean_data = []
for row in raw_data:
    clean_data.append( cleanup_row(row) )

Notice that the code calls a function called cleanup_row.  That function basically takes one row from the raw catalog data and goes through it cell by cell and cleans the data in each cell.  Cleaning the data consists of replacing the encoded tags with readable alternatives, replacing duplicate spaces with single spaces, and removing all characters that we don't want.  We create a string called legal_chars ahead of time, to specify which characters we consider legal for the output cells.  Here's the code:

legal_chars  = string.digits + string.ascii_letters + string.punctuation + ' '
def cleanup_row(row):
    def cleanup_element(element):
        t1 = element.replace('  ',' ').replace('&amp;','&').replace('&#8804;','<=').replace('&#8805;','>=').replace('&lt;','<').replace('&gt;','>')
        return ''.join([c for c in t1 if c in legal_chars])
    return [cleanup_element(element) for element in row]

We need to place this function above the code that uses it. In my program I have placed it right below the import statements.

Finally, we want to write the clean data out to a file.  For that I create an output file and call upon the Python csv module to write each row out to the file.   Just before I write out the rows of data, I write a row of labels so that the csv file has headings.

f = open('a4ca_catalog.csv','w')
writer = csv.writer(f,delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(['category','subtopic','title','link','agency','agencylink','format'])
for row in clean_data:
    writer.writerow(row)

That's it. We now have a .csv file that can be easily read by pretty much any spreadsheet or database program.

Here's the entire program with all the bits in order:
import read_a4ca_catalog
import string
import csv

legal_chars  = string.digits + string.ascii_letters + string.punctuation + ' '
def cleanup_row(row):
    def cleanup_element(element):
        t1 = element.replace('  ',' ').replace('&amp;','&').replace('&#8804;','<=').replace('&#8805;','&gt;=').replace('&lt;','<').replace('&gt;','>')
        return ''.join([c for c in t1 if c in legal_chars])
    return [cleanup_element(element) for element in row]

# read the a4ca catalog from the live web site
raw_data = read_a4ca_catalog.read_a4ca_catalog()

# clean the data
clean_data = []
for row in raw_data:
    clean_data.append( cleanup_row(row) )

# write the clean data out to a file
f = open('a4ca_catalog.csv','w')
writer = csv.writer(f,delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(['category','subtopic','title','link','agency','agencylink','format'])
for row in clean_data:
    writer.writerow(row)


And you can find the resulting csv file here.

The nice thing about doing this with a program rather than manually is that if the catalog is updated from time to time, all we have to do is run our program and we have a nice clean spreadsheet to work with that has the latest and greatest data.

Python comes with a lot of tools built in for manipulating data and it make short work of jobs like this. Now that the data is in spreadsheet form, we can look at it to see what different types of data there are, what format it's in and where it comes from, and we can do cross tabs and graphs to help us visualize those aspects.

28 April 2010

Data is Green

Of the three R's of responsible consumerism, I think the second R holds the most promise. The idea is that if you must buy something, then make it something durable and use it up.  This appeals to me.  If I spend a few extra bucks and purchase the durable good over the cheap one, I get to enjoy a superior product for longer.  And, as a bonus, I get to spend less of my life shopping.


On a recent trip to a small Mexican town I was struck by many cultural differences.  One of these was the extent to which things are used up.  Regardless of the motivation, it was clear that the residents of the town where I was staying were using things long after the point at which I personally would have discarded them.  From houses to automobiles to plastic containers to electronics to clothing and even food, things that I would have been comfortable with discarding here would continue to be used long after they made their way out of my life.

The Implications of Reuse for Data
As I was thinking about Reuse, it really struck me what an opportunity we have with our data.

We spend a lot of time and attention filling out forms and understanding terminology and concepts so that when we sign them, we know what we're doing and we get the services we need.  We do this when we want to interact with both governments and businesses.  We also provide the funds to enable government to collect all sorts of data about our resources, the places we live and the events that occur in our world so that we can be safe and secure and our resources utilized effectively.

We also spend money indirectly through taxes and fees to have that data stored, protected, backed up and maintained  by those public and corporate entities.  Its mind boggling to think about all the places my data resides and how many times my name, address and phone number are stored.

The data that we give  is only used for that one organization.  And, it's typically only used for the purpose it was collected for.

Why not find a way to store data so that it could be reused FOREVER by multiple parties?

Open Data and Reusability
If we were to add up all of the time, energy and resources required to store and manage our resource, geographical, financial and personal information and keep it locked up in hundreds or thousands of different locations, the impact on our environment must be significant.

Open Data allows that same data to be reused freely and infinitely for multiple purposes, so that we can maximize its value.  It also allows system developers to reduce their use of data because they don't have to reinvent data where it already exists.

I think Open Data represents an ultimate opportunity for reuse.  If data had a colour, it would have to be green.

19 April 2010

OpenDataBC: Accessing the A4CA Data Catalogue

The OpenDataBC Series: In this series of posts I will describe how to use some of the data that is being made available by the government of British Columbia on http://data.gov.bc.ca and related web sites.  My goal is to encourage people that might not otherwise consider interacting directly with data, to give it a try and see for themselves that it's easy, and maybe even fun.  :-)

Last week I sat down to have a closer look at the datasets that were released as part of the Province of BC's Apps 4 Climate Action (A4CA) contest.  I am very excited about the prospect of open data in BC and wanted to see what was available that might be interesting to use for various projects.

The A4CA data listed in the catalogue includes a range of formats and technologies.  Some are easier to work with than others.  Being able to browse the catalogue online is great but I really want to have a closer look and maybe do some analysis to find the data that is easy to work with.  For that I need to download the data so I can work with in it spreadsheet and / or database form.  In the perfect world, this data would be available on the site as a downloadable feed, with its own URL so programmers could simply point at the URL and get the data in XML format that goes with it.

The A4CA catalog provides a download to .CSV form, which is easy to work with but unfortunately, the link to that data is hidden behind a flash widget, so there is no way to download the data directly.  The page itself however does provide the data to the browser in the form of a table.  The table shows only 100 records at a time; however, there is another flash widget that allows the user to page through the data 100 records at a time, without a screen refresh.  That means the data is already in the browser, all 540 rows of it.  It's just a matter of scraping it out using a bit of code.

How it's done:
First, checking the robots.txt file for the site (www.gov.bc.ca) file reveals that the site allows for almost any type of program including this one, so that's great.

Prerequisites
My personal language of choice for this sort of task is Python, which comes pre-installed with all Linux and modern Mac machines and can be easily installed on Windows.  In my case I am using Python 2.6 under Ubuntu 9.10.  In addition to Python I am using Beautiful Soup which is an excellent library for scraping web sites.

The Code
The first thing we need to do in our program is to import the modules we need.  We are going to need urllib2 to grab the page and BeautifulSoup to parse it.  That's just one line:
import urllib2, BeautifulSoup

Next, we need to go out to the web and grab the HTML page and store it as a string called page:
page = urllib2.urlopen('http://data.gov.bc.ca/data.html')

Next, we create an object called soup using the BeautifulSoup library.
soup = BeautifulSoup.BeautifulSoup(page)

At this point we have the page loaded and we can read whatever parts of it we want using the methods provided by the soup object.

I am particularly interested in the table in the middle of the page, that contains the data I am after.  Looking at the raw HTML code from inside my browser I see that there is only one table on this page and that it's ID is set to 'example', so that makes it pretty easy to find using the find method provided by the soup object.
data_table = soup.find('table',id='example')

We also need a place to store our results.  I'll use an array for that.
records = []

Now that we have the table, we just want to cycle through the rows of the table and pull the data out.  For that we can use the Python for statement with the method findAll provided by the data_table object that we created.  With each row that we iterate through, we want to grab the text that is stored in each table cell.  This is easily accomplished by creating an array containing all of the cells in the row and then taking the parts we want to work with from that array.  Here's the code:

for row in data_table.findAll('tr'):
    if row.find('td'):
        cols = [a for a in row.findAll('td')]
        records.append([
            cols[0].text,
            cols[1].text,
            cols[2].text,
            cols[2].a['href'],
            cols[3].text,
            cols[3].a['href'],
            cols[4].text,
            ])

Pulling the text out of the table cells is as easy as accessing the .text member.  Two of the cells in each row have links, which I wanted to capture as well, so I accessed those by using the .a member and then access the href attribute which is where links are stored in HTML.

Now, each row in our records array contains one row from the table with the cell contents and links separated out.  This is a good start to making this data more usable for my purposes. 

Next, I plan to do some data cleaning and then start to do some analysis on it to get a feel for what's available in the A4CA catalogue.

And finally, here is the entire program:

def read_a4ca_catalog():
    import urllib2, BeautifulSoup

    page = urllib2.urlopen('http://data.gov.bc.ca/data.html')
    soup = BeautifulSoup.BeautifulSoup(page)

    records = []

    data_table = soup.find('table',id='example')
    for row in data_table.findAll('tr'):

        if row.find('td'):
            cols = [a for a in row.findAll('td')]
            records.append([
               cols[0].text,
               cols[1].text,
               cols[2].text,
               cols[2].a['href'],
               cols[3].text,
               cols[3].a['href'],
               cols[4].text,
               ])
    return records

if __name__ == '__main__':
    for record in read_a4ca_catalog():
        print record

With Python and BeautifulSoup it's easy to extract data from a site and I would encourage anyone to give it a try.  It's easier than you might think.

Now that we have the data in a form we can work with, how do we clean it up and make it more useful?  I'll cover that in the next article of this series.

17 April 2010

Real Time Notification System

At OpenGovWest I had the opportunity to hear about and discuss a host of innovative ideas involving open data and open government.  One of the most impressive examples that was discussed was OneBusAway, an excellent service that provides real time arrivals of transit buses.  When Brian Ferris introduced himself it was clear the whole room, including me, thought his service was a shining example of what was possible when open data is given a chance.

Brian's app is great for folks who use public transit now, and it makes mass transit even more convenient than it is already, so that goes some distance to reduce carbon emissions.  I got to thinking about that app and what else could be done with transportation and real time notification.  I was thinking what would it be like if grocery stores had rolling mini-marts that worked the same way, and notified you via an application or text message, that they were getting close.  They could have the basics (eggs, cheese, bread, milk, fresh fruits and vegetables) and you would be able to pop out to the street and get what you need.  No more time and gas wasted, and again, less carbon.

What if, indeed.

Fast forward one month, and I experienced this system first hand.  I found out that not only has this system been implemented but it's been in place for many years.  Some small Mexican villages have a scalable, just-in-time goods delivery system in place, complete with real time notification.  Goods ranging from bottled water to propane to fresh fruit and vegetables, fish, cheese and baked goods are transported throughout the city streets.  Families and business are notified 2 to 5 minutes in advance of deliveries the precise goods that will be soon passing through the neighbourhood.  The notification technology used is clean, inexpensive and emissions free and all mexican citizens and visitors are able to use this service for free.

It uses an oscillation of energy that moves through air, water, and other matter, in waves of pressure.  That's right.  Sound.

How does it work?

Vendors travel through the streets of the village either walking, by bicycle or in slow moving vehicles.  As they travel along they either verbally or through a recording, transmit a sound that is unique to them.  If it's a company the sound might be their trademark, if it's an individual entrepreneur she might have her own sound or she might simply announce what she is selling.  Consumers of goods can  hear these sounds from the streets, sidewalks or inside their homes, and because the sounds are distinct, they easily know what's coming.  The sounds are also loud and the vendors travel at a low rate of speed, so foks typically have several minutes to get their money together and prepare to meet the vendor at the door saving time, gas, money and the environment.

I think we sometimes get so caught up in our technology that we forget that there are often simpler, more basic solutions to some of the challenges we face today.  And many times, given the chance, these solutions will evolve on their own, without any grand design or oversite.  Instead of waiting for Apple to ship the next device,  subscribing to a 3G cell plan,  downloading the latest twitter client and then tweeting to my friends about what I am thinking, maybe I will just invite them to go for a walk or a bike ride so we can chat.

Adios amigos.

13 April 2010

On Apple's SDK License Changes

IBM used to sell mainframe computers where if you wanted more functionality, they would send an IBM technician to install a huge hardware module in your computer.  It was a closed controlled system and IBM could basically do whatever they wanted in terms of making hardware available and the way they decided to go was closed.  If you wanted that extra functionality, there was only one place to get it.  IBM.

Fast forward 50 years.  It seems a lot of developers are frustrated by the new Apple license changes.  It's getting more closed than before.  It’s easy to get frustrated when the rules change and it seems like you don’t have any say in how that goes, but, ultimately, that's the nature of a closed platform.  It's not a democracy; Apple makes the rules.

You can however choose whether or not to support it with your dollars, your attention or your time.  Closed works for Apple, and I love what Apple has done with mobile applications, music distribution and video rentals so I do spend some of my dollars there.

Ultimately though, I support open platforms because I think in the long run, they work better, they scale better, they cost less and they are the right thing to do.  That's why I choose to spend a lot of my money, attention and time working on Android and Linux and evangelizing open source, open data and open government.

11 April 2010

Don’t Make Me Register

You’ve worked hard to create your open data catalog and you’ve spent endless hours and resources creating the data that you are making available.  You want to make sure your data is used appropriately and you want to be able to protect your intellectual property.   You decide you want to put up a registration page so you can track who is downloading what data and how often they do so.  That way, you’re covered.  Sounds like a good strategy, right?  Wrong.

When you make registration mandatory people leave your site.

Here’s why:

When people are presented with an e-mail address form to access content the first question they are likely to ask themselves is, “why do you need this?”  Some sites will offer some sort of reasoning, like, “so we can keep you informed”, but then the person wonders, if that’s true, why is it mandatory?   What if I don’t want you to keep me informed?  It’s clearly not the real reason.  Strike one. You have just lost some trust with this person.

People are used to being lied to, so some will press on.  They know you don’t need their e-mail address but you are insisting on it anyway, so, the next logical question is: “What are you going to do with it?”.  A number of reasons come to mind but the one that will often come up first is you want to send them spam, or worse, you want to sell their email address to others who will send them spam.  So, now the person is faced with another decision:  “Should I use my real email address or should I use the one I reserve for sites that I don’t want to get spam from, or should I go to hotmail and make a new one for this site?”

If they manage to stay interested in your site for this long and go through with the e-mail registration, then at least you know they are highly motivated to get at your content.  If that’s your goal, to attract only highly motivated people (unfortunately this includes vandals) and eliminate the rest, then putting up a registration form might not be a bad way to go.

But there is a group of people in the middle, between the highly motivated people and the people who will never use your stuff.  This group in the middle live in an area called The Long Tail.  Promoting the generation of value from content like open data is all about The Long Tail, and if you want the people in the middle to participate and create value for you, you want to make their participation as easy as possible, so your population of users is as large as possible making the long tail as long as possible.

In the middle are the people who are motivated enough to check your site out and maybe even create something cool but who aren’t willing to potentially compromise their email address to do so.  By making them jump through hoops without a valid reason you are destroying trust at the very beginning of the relationship and potentially turning them away.

Using the word “mashup” gives the work a kind of fun sound, like it’s easy.  It’s not.  And currently, there are relatively few people who can take your data, combine it with some more data or perhaps some code, and make something truly valuable.  I am not saying you have to cater to these people, but if you really want them to choose your site to spend their time on, consider making it as easy as possible for them.

If your goal is to foster citizen engagement and to provide ways for people to contribute and maybe even crowd-source your data to produce a valuable outcome you should be looking to make the process as easy as possible and keep that tail as long as possible.  Requiring users to register themselves to download your data tells them that you value their e-mail address more than you value their contribution which, if true, means you might want to rethink your strategy.  There are easier ways to get people’s email addresses.

And if you have functionality that actually is valuable to the user, and requires people to sign in, consider a friendlier alternative like OpenID.

30 March 2010

OpenGovWest

I attended OpenGovWest last week.  Thought leaders and innovators of the western provinces of Canada and the western states of the USA came together to share ideas and collaborate around the topic of open government.  The conference was hosted by the City of Seattle and Knowledge as Power and was held in the beautiful Seattle City Hall.

Counted among the 200+ attendees were government leaders, public servants, analyists, software developers, university students, and private citizens, engaged and sharing ideas, issues, strategies and best practices in the open government space.  Our own BC made a huge contribution in terms of talent and participation, a tribute to the passion we have for our province.

Momentum at the grass roots level is building fast both here in BC and in the US.  The conference had a very engaged group and there was a lot of participation from most of the attendees, which in my experience is uncommon.  O'Reilly has their Gov 2.0 conference coming up in May in DC and I am sure it will be excellent and I think that perhaps many of us westerners would like to go but the expense of going to DC is hard for some to justify.  Going to Seattle was a great option.

Some of the topics discussed at OpenGovWest:

  • citizen engagement
  • public servant engagement
  • the barriers to opengov including: culture, fear, silos, legislation, status quo, lawsuits, excuses, etc..
  • how humans tend to focus on risk but ignore opportunity, the cost of "no"
  • open data licensing
  • open data structure, formats and accessibility
  • telling the story

I will be writing more about my thoughts in these areas in upcoming posts.  You can find other's opinions here and here and here.  Check out the ogw tag on twitter to see some of the ideas in raw form.

For those who are thinking that they might like to contribute but who think perhaps they can't make a difference, I would encourage you to get involved and take part in the discussions both online and at these conferences.  There are amazing people to meet and work with and it's an exciting time to be involved.

24 March 2010

Going to OpenGovWest

Heading to OpenGovWest this week.  I have been working on Open Data ideas for several months and have been watching the amazing progress the Sunlight Foundation has been making over the years.  Although I instinctively know that Open Data is the way of the future and that it will radically transform how governments at all levels operate (for the better) I still have trouble articulating that to others in tangible ways.  A worthy quest.  I will attend the conference this week to see if I can become more eloquent in describing the value that open data offers so that I can do my part here in BC to enroll others in the opportunity of open up BC data.

I suppose that ferreting out the business models for open data will take a while.  Look how long it took us to figure out how to make money from open source.  Learning from open source though, one can imagine, that the viable business models around open data, won't be around distributing the open data.  The winners  will be the folks who can add value to that data, to make that data consumable to others who can get more value from that data.  And that means understanding the data and the technology required to manipulate it.

So, in other words, it's a good time to be a geek.

13 March 2010

Book: I.O.U.

As part of my current effort to become more informed about the state of the country, economy and markets I recently finished reading I.O.U. by John Lanchester.  While Life Inc. described the nature of the corporation and the devastating effects it is having on humanity across the board, I.O.U. focuses specifically on the global financial crisis precipitated mostly by Wall Street and enabled by many others.

It's very comprehensible delve into the antics of modern banking and a "wake up call" to anyone who thinks the banks are 1) taking care of your money, or 2) care about your portfolio.  Your deposits are leverage for the real money, lending.

I highly recommend this book and though I think there are other ways to get this material this one is particularly good at showing how bizarre the financial world has become.

31 January 2010

Book: Life Inc.

I have recently become more and more interested in the state of our world on a macro level and on a recent trip to Vancouver I picked up a few books on the subject in an attempt to become more informed.  Call me naive but thus far in life I have just basically taken some things for granted: we live in a free market society, anyone can prosper if they are willing to work hard, real estate is a pretty safe long term investment, the government acts in the best interests of the people, etc...

I just finished reading one of the three books I picked up titled Life Inc. by Douglas Rushkoff.   Life Inc. is a book describing the effect of corporations and the power they have over us and our governments and the effect they are having on humanity.  If you've seen the movies "The Corporation" or "The Century of the Self" you have some idea of the material but this book takes it to a whole new level.  A highly recommended read I warn you, it's not the easiest material to consume.  Not that it's poorly written, or that it's alarmist, it isn't.  It's extremely well written and thoroughly researched and it's easy to read in a few days.

What's hard is grasping how insidious and yet subtle our current monetary system and the corporate system is.  Corporations are like a different life form, and they are competing with us for resources, and in the last 400 or so years, they have been winning.

It's not all bad news.  Douglas reminds us that we still have ultimate power, for now at least, and there are some very concrete things we can do.  It's just whether or not we have the will.  He states that the situation is entirely temporary.  We will either do what's needed to arrest corporatism, or... it will arrest us.

07 January 2010

Data.gov

I have been checking out the US Federal Government's open data site lately.  Imagine a country where citizens vote and elect a party to run the country.  Now imagine that the party decides where to spend money and one of the places they decide to spend money is in information technology and data and data warehousing and infrastructure and all sorts of other great things so they can track how the rest of your tax dollars are spent and what you got for it.  Now imagine they make that data available for free, no strings attached, to you, the citizens that paid for it.  It might not be as far off as we think.  Check out Data.gov.  This site belongs to the US of course, so it might be a while before we get a crack at something like this in Canada. (We don't even have Skype yet!)

28 August 2009

WordPress Hack Update (Google Reader)

As promised, I am sharing a remedy that I found this post in the wordpress.org site describing the problem I was having with WordPress. I have to say though, it frankly amazes me that WordPress is being hacked like that. I mean, it's been around a while. I would have expected it to be pretty hardened by now but in looking around for a remedy I read all kinds of horror stories about different exploits. Great interface, nice themes, pretty simple to use but I will not recommend it to my non-tech friends, even though it's open source, because of the security issues. It just requires too much technical knowhow to keep it running securely. Comments?

26 August 2009

(too) OpenID

Since I am getting totally into identity tech these days I figured it was about time to set up my OpenID and start using it myself. Being a Gmail user it seemed a no brainer to use my Google OpenID as my AP.

I checked the docs for my Google OpenID and presto whamo, I have my OpenID all set to go. Next, I decided that Facebook would be my first RP. So, after digging around on the web for a few minutes I found some instructions on how to do that. It's under Settings | Linked accounts. So easy.

So, I click on "Add" and up comes a list. There's Google, Yahoo and a bunch of others, so I pick OpenID and click "Link New Account" and Google comes up to verify that I am cool with the linkage. Nice. I check the list and Facebook wants my email address, cool, my Language, okay, makes sense and ... what... what's that... my Contacts? Facebook wants my Contacts List!?

No deal.

There is no option for me to just do authentication with Facebook using my Google account so I won't use my Google account. I am disappointed in Facebook (but not surprised).

Plan B. Looking for a nice OpenID provider that has nothing else to offer but my ID. :-)




07 August 2009

Google Reader Spam

Ugh! If you're using Google Reader to read this - well - you may not be able to read this because somehow some clever (but annoying) spammer has figured out how to inject spam into my posts for people using Google Reader. I would love to hear from any of my readers about a remedy for this. If I find one first, I will post it here.

Oh, and if you don't already know, I am using WordPress (for now).

(Note from Herb: As of December 2009 this site is now on Blogger)

05 August 2009

Upgrading my WP Site

I was recently hit with spam on this site so have finally upgraded to the latest and greatest version of WordPress.... it cost me nothing and I learned a cool technique for checking for blog spam... if there are more than two unique URL links in a post, it's probably spam so it gets held. Simple. I like it.


31 July 2009

OSCON 2009

As many of you know I had the privilege of attending OSCON 2009 last week. I just want to say, for the record, that it was easily the best conference I have ever been to. From the presentations, to the speakers to the BoFs, the whole thing was well organized, well executed and totally worth the 3,200 clicks I put on my motorcycle to get there. :-)

One of the things I got by going was the sense of community and the sense of contribution. Here were people from all walks of technology, from people just starting out to veterans of 20+ years, from database to Web 2.0 to Gov 2.0 to algorithm fanatics to social media creators all gathered to talk about their passion for creating, improving, using and championing free software. I am thrilled to do my part as a contributing member of these communities and am grateful for the opportunity.

The main takeaway though for me was the sense of leadership. The open source community is chock-full of leaders. People who dare to see and meet the call of something bigger than themselves and who are willing to stand for the result while it is only a possibility and who will act to make it real.

It's completely unreasonable to get an idea, collaborate with people all over the world in your spare time for months or years at a time, create world class software and then give it away for free to anyone who wants it, with no strings attached. And, that's exactly what is happening 24 hours a day 365 days of the year, all over the world.

It's completely unreasonable.

And it's so much fun.

Thanks OSCON for the excellent week. See you in 2010.

Ps: see some of the OSCON action by going to the OSCON site and viewing their videos of some of the talks.