-1

我有一个 xml 文件作为

<annotation>
    <folder>all_images</folder>
    <filename>0.jpg</filename>
    <path>/home/vishnu/Documents/all_images/0.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>4250</width>
        <height>5500</height>
        <depth>1</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>word</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>308</xmin>
            <ymin>45</ymin>
            <xmax>502</xmax>
            <ymax>162</ymax>
        </bndbox>
    </object>

我想使用 python 将此 xml 文件转换为文本文件,其中文本文件包含 xmin、ymin、xmax、ymax 的尺寸(值)。例如,我想将文本文件作为

308,45,502,45,502,162,308,162,字

663,52,823,52,823,173,663,173,word

521,44,621,44,621,158,521,158,word 

这个。..我有许多这样的 xml 文件,想将它们全部转换为文本文件。.还想循环它以获得这些文件的数量。

4

1 回答 1

2

假设您有一个名为 的文件file.xml,其中包含:

<annotation>
    <folder>all_images</folder>
    <filename>0.jpg</filename>
    <path>/home/vishnu/Documents/all_images/0.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>4250</width>
        <height>5500</height>
        <depth>1</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>word</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>308</xmin>
            <ymin>45</ymin>
            <xmax>502</xmax>
            <ymax>162</ymax>
        </bndbox>
    </object>
</annotation>

然后,同一文件夹中的以下 Python 脚本让您了解如何使用标准库ElementTree API来解析文件:

import xml.etree.ElementTree as ET

tree = ET.parse("file.xml")
root = tree.getroot()

print(root.find("./folder").text)
print(root.find("./object/name").text)
print(root.find("./object/bndbox/xmin").text)

您需要弄清楚如何将值写入您自己的文本文件,但这应该很简单。有很多这样的资源

于 2018-11-12T13:29:44.170 回答