从xml文件中获取坐标(x,y),并将其放入浮点列表中

2024-09-28 21:56:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把从xml文件中恢复的几个坐标(x,y)放在一个列表中,可以与drawcontour或polyline函数一起使用 问题是我不知道如何将它们放入我使用的liste.append列表中,但它不起作用:(请帮助我)

<?xml version="1.0" ?>
<TwoDimensionSpatialCoordinate>
    <coordinateIndex value="0"/>
        <x value="302.6215607602997"/>
        <y value="166.6285651861381"/>
    <coordinateIndex value="1"/>
        <x value="3.6215607602997"/>
        <y value="1.6285651861381"/>
</TwoDimensionSpatialCoordinate>
import xml.dom.minidom


def main(file):
    doc = xml.dom.minidom.parse(file)
    values = doc.getElementsByTagName("coordinateIndex")
    coordX = doc.getElementsByTagName("x")
    coordY = doc.getElementsByTagName("y")
    d = []
    for  atr_x in  coordX:
        for   atr_y in  coordY:
            x = atr_x.getAttribute('value')
            y = atr_y.getAttribute('value')
            print("x",x,"y",y)
    d.append(x)
    d.append(y)
    print(d)


result = main('1.631791322.58809740.14.834982.40440.3641459051.955.6373933.1920.xml')
print(result)

输出:

x 302.6215607602997 y 179.53418754193044
x 317.14038591056607 y 179.53418754193044
x 328.11016491298955 y 179.53418754193044
x 337.6280614003864 y 179.53418754193044
x 350.0497229178365 y 179.53418754193044
x 363.9232669503133 y 179.53418754193044

这个结果是当我从xml文件获得x,y坐标时,但当我添加d.append时,它没有定义dNameError: name 'd' is not defined


Tags: 文件列表docvaluemainxmldomfile
2条回答
  1. 您的XML很奇怪(xy不在coordinateIndex
  2. python中的缩进问题
  3. 您可能想尝试ElementTree,它被认为是minidom的更好的替代品
  4. minidom和输入格式的工作代码
def main(file):
    doc = xml.dom.minidom.parse(file)
    coordX = doc.getElementsByTagName("x")
    coordY = doc.getElementsByTagName("y")
    d = []
    for atr_x, atr_y in zip(coordX, coordY):
        x = atr_x.getAttribute('value')
        y = atr_y.getAttribute('value')
        print("x", x, "y", y)
        d.append(x)
        d.append(y)
    return d

现在是工作了:我把代码放在万一以后有人需要的地方

import xml.dom.minidom
import cv2 
import numpy as np
import matplotlib.pyplot as plt



def main(file):
    doc = xml.dom.minidom.parse(file)
    coordX = doc.getElementsByTagName("x")
    coordY = doc.getElementsByTagName("y")
    d = []
    for atr_x, atr_y in zip(coordX, coordY):
        x = atr_x.getAttribute('value')
        y = atr_y.getAttribute('value')
        #print("x", x, "y", y)
        d.append(x)
        d.append(y)

    a = map(float, d)
    print(tuple(zip(a, a)))

    return a  

result = main('1.631791322.58809740.14.834982.40440.3641459051.955.6373933.1920.xml')
print(result)

相关问题 更多 >