question about dictionary type..
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
> 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))
"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
More information about the Python-list