[Tutor] Newbie

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 18 Feb 2002 14:59:37 -0800 (PST)


On Mon, 18 Feb 2002, Nicole Seitz wrote:

> def AddWord( ):
>          global new_category
> 
>          new_word = raw_input("New word: ")
>          new_category = raw_input("Category: ")
>          new_entry ="\n"+ new_word + " "+ new_category
>          file = open('lexicon.txt','a')
>          file.write(new_entry)
>          file.close()
> -------------------------------------------------------------------------------
> So far, so good. This works somehow.But unfortunately, after adding a new 
> word, the lexicon isn't sorted anymore.
> For example, I could have
> [...]
> sleep vi
> fish vi
> 
> their det
> the det
> an det
> a det
> 
> big adj
> good adj
> Paris n   #DOn't want the new entry HERE!!!!!!!!
> 
> --------------------------------------------
> So, how can I keep my lexicon sorted?


Hi Nicole,


At the moment, the AddWord() function appends a new lexicon entry into the
file, so all new entries are "tacked on" in the back.  One approach to
keep the lexicon sorted is to load the lexicon into memory, sort the
lexicon and then write the whole lexicon back to the file.

Python lists have a 'sort()' method that you can use to make this work.  
Here's an interpreter session that may help:


###
>>> names = ['fish', 'sleep', 'their', 'the', 'an', 'big', 'good',
'paris']
>>> names.sort()
>>> names
['an', 'big', 'fish', 'good', 'paris', 'sleep', 'the', 'their']
###

If we want to have the function sort in a different way, we can pass the
sort() method an optional "comparision function" that tells it how two
elements compare to each other.

For example, let's say that we'd like to sort these strings by length.  We
can write this comparision function:

###
>>> def cmp_by_length(word1, word2):
...     return cmp(len(word1), len(word2))
... 
>>> names.sort(cmp_by_length)
>>> names
['an', 'big', 'the', 'fish', 'good', 'paris', 'sleep', 'their']
###


I'm sorry I'm rushing things; I'm getting hungry and must get big, fishy
french food.  mmm... fooo...good...


Please feel free to ask more questions.  Good luck to you!