在Python中使用循环从XML文件中提取字符串 [英] Extracting String from XML files with loop in Python

查看:120
本文介绍了在Python中使用循环从XML文件中提取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有14个这样的XML文件,我正在尝试获取ActionUnit Number值(例如45和5).我也需要对其他13个XML文件进行循环处理.之后,我需要为提取的每个值创建子文件夹.我尝试使用代码进行值提取,但结果一无所获;

I have 14 different XML files like this and I'm trying to get ActionUnit Number values (ex. 45 and 5). I need to do it for the other 13 XML files too with a loop. After that, I need to create subfolders for each value that I extracted. I tried a code for value extraction but I get none as a result;

import xml.etree.cElementTree as ET

tree= ET.ElementTree(file=r'C:\Users\LME_s\Desktop\python quiz\Sessions\1\S001-001-oao_aucs.xml')
root= tree.getroot()
for chld in root:
   print (chld.get('ActionUnit Number'))

推荐答案

您的问题实际上是几个问题...这是从xml中提取所需数据的方法.

Your question is actually few questions... Here is how to extract the data you need from the xml.

import xml.etree.ElementTree as ET

XML = '''<ActionUnitCoding>
            <ActionUnit Number="45"></ActionUnit>
            <ActionUnit Number="5"></ActionUnit>
        </ActionUnitCoding>'''
root = ET.fromstring(XML)
numbers = [e.attrib['Number'] for e in root.findall('.//ActionUnit')]
print(numbers)

输出

['45', '5']

这篇关于在Python中使用循环从XML文件中提取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆