我正在解析XML文件并获得一个元组作为回报。我将元组转换为str然后转换为字典。我想获得Lanestat的关键和价值。例如:Lanestat,键1并获得值2。 但代码不优雅,欣赏任何建议。 TQ
的xml:
- <Test>
- <Default_Config>
<LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK>
<Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat>
</Default_Config>
</Test>
输出:
('LINK', '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
('Lanestat', '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
<type 'tuple'>
<type 'str'>
<type 'dict'>
2
代码:
import elementtree.ElementTree as ET
tree = ET.parse("dict1.xml")
doc = tree.getroot()
for elem in doc.findall('Default_Config/LINK'):
a=elem.tag, elem.text
print a
for elem in doc.findall('Default_Config/Lanestat'):
a=elem.tag, elem.text
print a
print type(a)
b=a[1]
print type(b)
c=eval(b)
print type(c)
print c[1]
答案 0 :(得分:4)
您可以使用 ast.literal_eval() 安全地将 elem.text 解析为dict:
import ast
for elem in doc.findall('Default_Config/Lanestat'):
if elem.tag == 'Lanestat':
val = ast.literal_eval(elem.text)
print type(val), val
print elem.tag, val[1]
输出:
<type 'dict'> {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}
Lanestat 2
已更新:以下是backport of literal_eval to Python 2.4/2.5,我已在此处粘贴代码以修复次要格式问题:
from compiler import parse
from compiler.ast import *
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, numbers, tuples,
lists, dicts, booleans, and None.
"""
_safe_names = {'None': None, 'True': True, 'False': False}
if isinstance(node_or_string, basestring):
node_or_string = parse(node_or_string, mode='eval')
if isinstance(node_or_string, Expression):
node_or_string = node_or_string.node
def _convert(node):
if isinstance(node, Const) and isinstance(node.value,
(basestring, int, float, long, complex)):
return node.value
elif isinstance(node, Tuple):
return tuple(map(_convert, node.nodes))
elif isinstance(node, List):
return list(map(_convert, node.nodes))
elif isinstance(node, Dict):
return dict((_convert(k), _convert(v)) for k, v
in node.items)
elif isinstance(node, Name):
if node.name in _safe_names:
return _safe_names[node.name]
elif isinstance(node, UnarySub):
return -_convert(node.expr)
raise ValueError('malformed string')
return _convert(node_or_string)
print literal_eval("(1, [-2, 3e10, False, True, None, {'a': ['b']}])")
输出:
(1, [-2, 30000000000.0, False, True, None, {'a': ['b']}])