xml.etree.ElementTree.ParseError:格式不正确(令牌无效):-将包含xml文件的文件夹转换为csv文件时

时间:2018-07-19 15:15:18

标签: python xml csv parse-error

这是将名为test的子文件夹转换为名为xml的父文件夹的python脚本,并转换为csv文件 使用tensorflow api进行物体检测以标记卫星图像

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET

def xml_to_csv(path):
    xml_list = []
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                      int(root.find('size')[1].text),
                       member[0].text,
                      int(member[4][0].text),
                 int(member[4][1].text),
                 int(member[4][2].text),
                 int(member[4][3].text)
                 )
         xml_list.append(value)
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df


def main():
for folder in ['train','test']:
    image_path = os.path.join(os.getcwd(), ('images/' + folder))
    xml_df = xml_to_csv(image_path)
    xml_df.to_csv(('images/' + folder + '_labels.csv'), index=None)
    print('Successfully converted xml to csv.')



main()

并收到此错误

    File "xml_to_csv.py", line 37, in <module>
    main()
  File "xml_to_csv.py", line 31, in main
    xml_df = xml_to_csv(image_path)
  File "xml_to_csv.py", line 10, in xml_to_csv
    tree = ET.parse(xml_file)
  File "C:\Users\asus\Anaconda3\envs\tensorflow1\lib\xml\etree\ElementTree.py", line 1196, in parse
    tree.parse(source, parser)
  File "C:\Users\asus\Anaconda3\envs\tensorflow1\lib\xml\etree\ElementTree.py", line 597, in parse
     self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 2,    column 5

我尝试查看编码是否没有问题,但似乎对产生错误没有任何影响。 这是由于标记卫星图像而生成的xml代码(共500个)。

<annotation>
<folder>train</folder>
<filename>windmill8.jpg</filename>
<path>C:/tensorflow1/models/research/object_detection/images/train/windmill8.jpg</path>
<source>
    <database>Unknown</database>
</source>
<size>
    <width>1538</width>
    <height>820</height>
    <depth>3</depth>
</size>
<segmented>0</segmented>
<object>
    <name>windmill</name>
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <difficult>0</difficult>
    <bndbox>
        <xmin>270</xmin>
        <ymin>713</ymin>
        <xmax>337</xmax>
        <ymax>766</ymax>
    </bndbox>
</object>

请告诉我们如何解决此问题?

0 个答案:

没有答案