paseline(my favorite simple script): does something similar exist?

skip at pobox.com skip at pobox.com
Thu Oct 12 15:35:40 EDT 2006


    Rick> def parseline(line,format):
    Rick>     xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
    Rick>     result = []
    Rick>     words = line.split()
    Rick>     for i in range(len(format)):
    Rick>         f = format[i]
    Rick>         trans = xlat.get(f,'None')
    Rick>         if trans: result.append(trans(words[i]))
    Rick>     if len(result) == 0: return None
    Rick>     if len(result) == 1: return result[0]
    Rick>     return result

Note that your setting and testing of the trans variable is problematic.  If
you're going to use xlat.get(), either spell None correctly or take the
default:

    trans = xlat.get(f)
    if trans:
        result.append(trans(words[i]))

As Paul indicated though, it would also be better to not to silently let
unrecognized format characters pass.  I probably wouldn't let KeyError float
up to the caller though:

    trans = xlat.get(f)
    if trans:
        result.append(trans(words[i]))
    else:
        raise ValueError, "unrecognized format character %s" % f

Finally, you might consider doing the splitting outside of this function and
pass in a list.  That way you could (for example) easily pass in a row of
values read by the csv module's reader class (untested):

    def format(words, fmt):
        xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
        result = []
        for i in range(len(fmt)):
            f = fmt[i]
            trans = xlat.get(f)
            if trans:
                result.append(trans(words[i]))
            else:
                raise ValueError, "unrecognized format character %s" % f
        return result

    Rick> I'm posting this here because (1) I'm feeling smug at what a
    Rick> bright little coder I am, and (2) (in a more realistic and humble
    Rick> frame of mind) I realize that many many people have probably found
    Rick> solutions to similar needs, and I'd imaging that many are better
    Rick> than the above. I would love to hear how other people do similar
    Rick> things.

It seems quite clever to me.

Skip



More information about the Python-list mailing list