Brandon's Blog

7/3/2006

Magical Mystery Tour

I want to take you on a journey with the Python language and libraries.  I want you to see what they can do (the three >’s is a prompt).

>>> s = " 'get a' cookie now "
>>> s
" 'get a' cookie now "
>>> import shlex
>>> shlex.split(s)
['get a', 'cookie', 'now']

Bam.  Now, let’s introduce a little more complexity.  Let’s say there are two cookies: one is normal, and the other is enchanted (in that search order).  The enchantment does not modify anything in the way of a name or description.  You need to get the second one.  The “get a” token is not realistic; simply to brag on the quoting capabilities of both the language and the shlex parser.

Let’s allow the player to say, “with respect to the search order [the natural, incidental order of the relevant linked list of items], select the nth cookie.”  He can say this by appending ”#n” to the end of the proper token.  All other #’s in the token, besides the last one, are to be ignored.

>>> s = “ ‘get a’ cookie#2 now “
>>> s
“ ‘get a’ cookie#2 now “
>>> shlex.split(s)
[‘get a’, ‘cookie#2’, ‘now’]
>>> a = shlex.split(s)[1]
>>> a
‘cookie#2’
>>> a.rsplit(‘#’, 1)
[‘cookie’, ‘2’]

And, for the picky…

>>> s = “ ‘get a’ cookie#3#2 now “
>>> s
“ ‘get a’ cookie#3#2 now “
>>> shlex.split(s)
[‘get a’, ‘cookie#3#2’, ‘now’]
>>> a = shlex.split(s)[1]
>>> a
‘cookie#3#2’
>>> a.rsplit(‘#’, 1)
[‘cookie#3’, ‘2’]

That’s what I mean by “Legos.”