如何解决如何直接将代码应用于所有文件并将xml文件转换为txt文件
我正在尝试在python中应用代码以从每个xml文件中提取必要的信息,并将其写入txt文件中。 我成功执行了代码,但结果仅显示一个文件。 另外,我的代码看起来并不聪明,如果有人可以帮助我解决问题并给予纠正,我将非常高兴。
恐怕我是个初学者,所以我可能会有很多基本的错误...
这是我的代码
from xml.etree import ElementTree as ET
import os
path = r'/Users/mo/Documents/annotations/xmls'
filenames = []
for filename in os.listdir(path):
if not filename.endswith('.xml'):
continue
fullname = os.path.join(path,filename)
filenames.append(fullname)
each_name = filename[:-4]
with open(each_name + '.txt','a') as f:
for filename in filenames:
tree = ET.parse(filename)
root = tree.getroot()
for object in root.findall('object'):
categoryID = object.find('name').text
for bnd_box in object.findall('bndbox'):
Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'
f.write(str(Detection_rows))
非常感谢您
解决方法
尝试一下(未测试)
from xml.etree import ElementTree as ET
import os
path = r'/Users/mo/Documents/annotations/xmls'
for filename in os.listdir(path):
if not filename.endswith('.xml'):
continue
fullname = os.path.join(path,filename)
with open(fullname[:-4] + '.txt','a') as f:
tree = ET.parse(fullname)
root = tree.getroot()
for object in root.findall('object'):
categoryID = object.find('name').text
for bnd_box in object.findall('bndbox'):
Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'
f.write(str(Detection_rows))
您的for循环应位于open
之外,并且您将filenames
更改为filename
。另外,我删除了一个不必要的for循环。让我知道它是否可以为您解决问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。