question about dictionary type..

Frank Buss fb at frank-buss.de
Tue Sep 17 10:53:17 CEST 2002


eugene kim <eugene1977 at hotmail.com> wrote:

> i read a python book while ago, and trying to refamiliaze myself with it 
> recently, your solution looks so cool..

Thanks, I'm not a Python expert, because I wrote my first line of Python 
code one month ago (but I already knew some other languages), so there are 
probably a better solution for your problem using Python. But for me it 
was a good idea to help in this newsgroup for learning a bit more of 
Python :-)

> have to spend some time what u did =)

The add-funtion is obvious. So looking at the main program:

records = re.compile('\((.*?)\)', re.DOTALL).findall(stdin.read())
for record in records:
  fields = map(lambda w: upper(w), re.findall("'(.*)'", record))
  add(tree, (fields[0],fields[2],fields[3]),0)
  add(tree, (fields[1],fields[2],fields[3]),0)

"stdin.read()" reads all from stdin. ".*" matches any chars (zero or more 
occurence). It is written within a group (the '(' and ')'), so findall can 
use the matching result. Because your records are surrounded by '(' and 
')' I wrote '\(' and '\)'. The "?" is needed to avoid greedy matching. 
Without "?" only one record would be matched, starting from the first "(" 
until the last ")" in the whole file. "re.DOTALL" says, that "." should 
match newslines, too.

Next interesting expression is the map-line. "'(.*)'" matches anything 
between two '. It doesn't need to be non-greedy ("?"), because the line 
boundarys are not matched (no re.DOTALL). The result is a list of all 
fields. "map" iterates through all elements of the resulting list, applys 
the function "upper" through the lambda-inline-function to each element 
and returns a new list with the upper-cased elements.

-- 
Frank Buß, fb at frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de



More information about the Python-list mailing list