Parsing a string which represents a list of tuples

落花浮王杯 提交于 2019-11-30 11:27:11
>>> import ast
>>> print ast.literal_eval("(8, 12.25), (13, 15), (16.75, 18.5)")
((8, 12.25), (13, 15), (16.75, 18.5))
def parse(s):
    tuples = s.split('), ')
    out = []
    for x in tuples:
        a,b = x.strip('()').split(', ')
        out.append((float(a),float(b)))
    return out

this should do the job.

Ned Batchelder

I've used safe_eval for jobs like this in the past.

If you're working with a CSV file, and you want more than the "naive" solution which doesn't handle any errors, you're probably best off using the Python's CSV module.

Download PyParsing.

I've worked with it before. You can get some pretty robust parsing behavior out of it, and I think it provides builtins that will handle your entire parsing needs with this sort of thing. Look up commaSeparatedList and nestedExpr.

what's wrong with doing it systematically ? split on ")", then go through the list, remove all "(".

>>> s="(8, 12.25), (13, 15), (16.75, 18.5)"
>>> [ i.replace("(","") for i in s.split(")") ]
['8, 12.25', ', 13, 15', ', 16.75, 18.5', '']
>>> b = [ i.replace("(","") for i in s.split(")") ]
>>> for i in b:
...  print i.strip(", ").replace(" ","").split(",")
...
['8', '12.25']
['13', '15']
['16.75', '18.5']
['']

Now you can bring each element into your data structure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!