开发者

What is the best way to parse a tuple from a string in Python?

开发者 https://www.devze.com 2023-03-10 08:29 出处:网络
I tried this: def string_to_value(self, old_value, distribution_type, new_value_str): parameter_names = distribution_type.parameters# a list of string

I tried this:

def string_to_value(self, old_value, distribution_type, new_value_str):
    parameter_names = distribution_type.parameters  # a list of string
    try:
        parameter_values = ast.literal_e开发者_Python百科val(new_value_str)  # a tuple or basic type hopefully
    except SyntaxError:
        raise ValueError('Syntax error during parse')
    retval = copy.copy(old_value)
    try:
        if len(parameter_names) == 1:
            setattr(retval, parameter_names[0], parameter_values)
        else:
            if len(parameter_names) != len(parameter_values):
                raise BoostPythonArgumentError
            for parm_name, parm_value in zip(parameter_names,
                                             parameter_values):
                setattr(retval, parm_name, parm_value)
    except BoostPythonArgumentError:
        raise ValueError('Lots of helpful text here')
    return retval

This works for a lot of cases. Boost.Python automatically checks the type of parm_value at set time. Unfortunately, it doesn't work on strings containing 'inf'. ast.literal_eval raises ValueError('malformed string') when I would like it to return a float. I don't understand how Python can parse 'inf', but literal_eval can't.


Check this documentation and this PEP about evaluating inf. I guess they will help


Do you need to evaluate? e.g.

a = "(1,2,3,4)"
b = tuple(a.strip('( )').split(','))
assert ('1','2','3','4') == b


If all the elements have the same numeric type, then this works:

numpy.fromstring('1.3, 2.2, 5, inf, 2', sep=',')

returns

array([ 1.3,  2.2,  5. ,  inf,  2. ])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号