How to do a Lispy-esque read?

Barrett Lewis musikal.fusion at gmail.com
Mon Apr 8 04:17:57 EDT 2013


> For example, if the input stream contained the text:
> [1, # python should ignore this comment
> 2]
>
> and I do a "read" on it, I should obtain the result
> [1, 2]
> --
>

I don't know much about lisp but given that input and the desired output
you can write functions like the following

def strtolist(l):
    if l.startswith('['):
        l = l[1:]
    if l.endswith(']'):
        l = l[:-1]

    # treat newlines as if they are commas so we can easily split
    l = l.replace('\n', ',').split(',')
    # list comprehension
    # strip to remove whitespace and aggregate all elements without the
comment
    # you can further refine this to create ints by using the int() method
    return [x for x in l if not x.strip().startswith('#')]

you would have to use input() to read the input or open a file. Either way
you can pass that value to strtolist and it will convert it to a list of
strings.
However, this implementation is not very robust and doesn't cover a lot of
edge cases (more a demo of how it might be done, I don't know your python
experience so forgive me if this is all self evident).

The real solution that I would use would be to use the json module.
Docs: http://docs.python.org/3.3/library/json.html
It allows you to take a string and turn it into a native dict or list in
python. The great part is that it is fairly robust and it has a simple
interface. You could take input() and send it to loads and it will return
an array. The downside is json doesn't allow comments.

If you really want comments, you could look into some of the yaml
libraries, a quick google search shoes PyYaml is out there. I however don't
have any knowledge of that module or other yaml modules as I find json is
enough for anything I've ever attempted.

I hope that helps
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130408/9d0f072a/attachment.html>


More information about the Python-list mailing list