python - 使用 Python 从 XML 解析矩阵

标签 python xml numpy matrix

假设我有一个以下列格式存储在 XML 文件中的矩阵:

<?xml version="1.0"?>

<Matrix>
    <Value Col="0" Row="0">0.19343</Value>
    <Value Col="1" Row="0">0.95079</Value>
    <Value Col="2" Row="0">0.89542</Value>
    <Value Col="0" Row="1">0.14391</Value>
    <Value Col="1" Row="1">0.094629</Value>
    <Value Col="2" Row="1">0.52303</Value>
</Matrix>

在不知道矩阵维度大小的情况下,使用 Python 中的 xml.etree 将这些值解析为 numpy 数组的最佳方法是什么??否则,我想我可以简单地做:

import xml.etree.ElementTree as ET
import numpy as np

rowcnt = 2
colcnt = 3

xmltree = ET.parse('some_xmlfile.xml')
matrix = np.zeros(shape=(rowcnt, colcnt))

for m in xmltree.iter('Matrix'):
    for v in m.iter('Value'):
        col = int(v.attrib['Col'])
        row = int(v.attrib['Row'])
        matrix[row, col] = float(v.text)
    print matrix

最佳答案

我并不是说这是从 XML 文件创建 numpy 数组的最佳方法,但这应该适用于任意数量的列(尽管行的大小必须相同), 以及任意排序的 <Value>元素。

import numpy as np
import xml.etree.ElementTree as ET
from collections import defaultdict

root = ET.parse('some_xmlfile.xml').getroot()

data = defaultdict(list)

# group into rows of (col, val) tuples
for val in root.iter('Value'):
    data[int(val.attrib['Row'])].append((int(val.attrib['Col']), val.text))

# sort columns and format into a space separated string
rows = []
for row in data:
    rows.append(' '.join([cols[1] for cols in sorted(data[row])]))

# build array from matrix string
matrix = np.array(np.mat(';'.join(rows)))


>>> matrix
array([[ 0.19343 ,  0.95079 ,  0.89542 ],
       [ 0.14391 ,  0.094629,  0.52303 ]])

关于python - 使用 Python 从 XML 解析矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25203549/

相关文章:

python - 标量的奇怪 numpy 划分行为

python - 当一种数据类型是对象时,numpy 掩码数组的行为有所不同

python - Windows XP 上的 Scrapy ImportError : No module named w3lib. html

python - 使用 numpy 创建特定数组

xml - XML 元素的自定义排序

xml - 在 xslt 中格式化日期

c++ - TinyXML 遍历元素

python - 类如何生成根据类属性而变化的回调函数?

python - Perl 到 Python 正则表达式

python - 为什么一个 352GB 的 NumPy ndarray 可以用在 8GB 内存的 macOS 电脑上?