My Life As A Blog

Sorting results in Python

leave a comment »

After yesterday’s exercise, I decided that today it’d be good to be able to retrieve the results.  And I’d like the results to be sorted.  A quick trawl across the internet and I found this post about sorting dictionaries in Python.  For an introduction to sorting in Python, this article is helpful.  So, I modified the Reader class by adding an import statement:

from operator import itemgetter

I took out the result printing loop and added a new function:

def get_sorted_results(self):
    return sorted(, key=itemgetter(1), reverse=True)

And that’s it.  To see the sorted results, here’s some code entered into the interactive shell:

>>> from TextProcessor import Reader
>>> reader = Reader()
>>> list = ["This is a multiline string.\nWith many lines.", "This isn't.", "And nor is this."]
>>> for key, value in reader.get_sorted_results():
...     print key, value
this 3
is 2
a 1
and 1
string 1
many 1
lines 1
multiline 1
nor 1
with 1
isn't 1

The next step would seem to be displaying the results in something other than a console.


Written by remark

January 7, 2010 at 6:18 pm

Posted in Development, Python

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: