简体   繁体   English

将字符串解析为 namedtuple object

[英]Parse String into namedtuple object

How to read back string, into namedtuple?如何将字符串读回命名元组?

import collections
from typing import Sequence, Iterator
import ast

Range = collections.namedtuple("Range", ["key", "min", "max", "in_range" ])

Ranges to string范围到字符串

Test object to string:测试 object 到字符串:

r1 = tools.Range(key='T1',min=-0.01,max=0.19, in_range=True)
r2 = tools.Range(key='T2',min=2,max=10, in_range=False)
r3 = tools.Range(key='T3',min=225000,max=1583515.5, in_range=True)
rs = [r1, r2, r3]
rstr = str(rs)
print(rstr) 
# output:
# [Range(key='T1', min=-0.01, max=0.19, in_range=True), Range(key='T2', min=2, max=10, in_range=False), Range(key='T3', min=225000, max=1583515.5, in_range=True)]

How to read same or similar string now into object (list of Range)?现在如何将相同或相似的字符串读入 object(范围列表)?

Parse back String to Ranges将字符串解析回范围

What I've tried with most hope of success:我最希望成功的尝试:

source_string = "[Range(key='T1', min=-0.01, max=0.19, in_range=True), Range(key='T2', min=2, max=10, in_range=False), Range(key='T3', min=225000, max=1583515.5, in_range=True)]"
source = ast.literal_eval(source_string)
ranges = tools.Range(key=source["key"],min=float(source["min"]), max=float(source["max"]), in_range=bool(source["in_range"]))

I did also variants, with no success.我也做了变种,但没有成功。 I am open to change the string syntax to get the ranges object generate.我愿意更改字符串语法以获取 object 生成的范围。

The ast.literal_eval function can only parse the following types: ast.literal_eval function 只能解析以下类型:

  • strings字符串
  • bytes字节
  • numbers数字
  • tuples元组
  • lists列表
  • dicts听写
  • sets
  • booleans布尔值
  • None and Ellipsis无和省略号

This also means that it can only parse a tuple, list, dict, or set containing these specific types.这也意味着它只能解析包含这些特定类型的元组、列表、字典或集合。 It cannot parse a list of namedtuple objects.它无法解析namedtuple对象的列表。 So you will have to either:所以你将不得不:

  1. Create your own method that parses a string of the format "Range(key=...(etc.)" , OR创建您自己的方法来解析格式为"Range(key=...(etc.)"的字符串,或者
  2. Remove the attribute names/keywords from your string, leaving simply a tuple for each element.从字符串中删除属性名称/关键字,只为每个元素留下一个元组。 You can then use python's built-in map function in combination with the namedtuple._make method to parse the list of tuples:然后可以使用 python 的内置map function 结合namedtuple._make方法来解析元组列表:
source_string = "[('T1', -0.01, 0.19, True), ('T2', 2, 10, False), ('T3', 225000, 1583515.5, True)]"
source = ast.literal_eval(source_string)
ranges = list(map(Range._make, source))

If you really need Range(...) and/or key=..., min=... to be a part of the string, you could potentially pre-process the string using regex.如果您确实需要Range(...)和/或key=..., min=...作为字符串的一部分,您可以使用正则表达式对字符串进行预处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM