【问题标题】:python numpy array convert to xmlpython numpy数组转换为xml
【发布时间】:2021-08-24 15:22:19
【问题描述】:

例如,有我的数据:

import numpy as np
a = np.array([[ 26.2, 280. ],
       [ 26.2, 279. ],
       [ 26. , 278.8],
       [ 25.2, 278. ],
       [ 25. , 277.8],
       [ 24.2, 277. ],
       [ 24. , 276.8],
       [ 23. , 276.8],
       [ 22.8, 277. ],
       [ 23. , 277.2],
       [ 23.8, 278. ],
       [ 24. , 278.2],
       [ 24.8, 279. ],
       [ 25. , 279.2],
       [ 25.8, 280. ],
       [ 26. , 280.2],
       [ 26.2, 280. ]])

我想要一个这样的 xml 苍蝇:

<?xml version="1.0"?>
<ASAP_Annotations>
    <Annotations>
        <Annotation Name="Annotation 0" Type="Spline" PartOfGroup="_1" Color="#F4FA58">
            <Coordinates>
                <Coordinate Order="0" X="26.2" Y="280." />
                <Coordinate Order="1" X="26.2" Y="279. " />
                <Coordinate Order="2" X="26." Y="278.8" />
                .........
                .........
                .........
                <Coordinate Order="14" X="25.8" Y="280." />
                <Coordinate Order="15" X="26." Y="280.2" />
                <Coordinate Order="16" X="26.2" Y="280." />
            </Coordinates>
        </Annotation>
    </Annotations>
</ASAP_Annotations>

我知道可能是xml.etree.ElementTree实现的,但是我没学过,能不能告诉我用python怎么做,谢谢~

【问题讨论】:

标签: python xml numpy xml.etree


【解决方案1】:

一个简单的 for 循环就可以做到这一点:

headerXML = '''<?xml version="1.0"?>
<ASAP_Annotations>
    <Annotations>
        <Annotation Name="Annotation 0" Type="Spline" PartOfGroup="_1" Color="#F4FA58">
            <Coordinates>
'''

elements = ""

i = 0
for element in a:
    elements = elements+ '<Coordinate Order="%s" X="%s" Y="%s" />\n'% (i,element[0],element[1] )
    i = i + 1


footerXML = '''
            </Coordinates>
        </Annotation>
    </Annotations>
</ASAP_Annotations>
'''

XML =(headerXML+elements+footerXML)

outFile = open("coordinates.xml","w")
outFile.write(XML)
outFile.close()

【讨论】:

  • 您能告诉我如何将其写入 xml 文件吗?
  • 再看一遍,我删除了第一行是空行
猜你喜欢
  • 1970-01-01
  • 2021-11-29
  • 2015-12-04
  • 2018-09-19
  • 2022-01-03
  • 2015-12-26
  • 2012-01-17
  • 2017-02-13
  • 1970-01-01
相关资源
最近更新 更多