python - 使用python解析多个xml文件
问题描述
我在一个文件夹中有多个 xml 文件。我想解析所有的 xml 文件。我尝试过 minidom 解析,但我做不到。这是xml文件就像-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="frame.xsl"?>
<frame cBy="KmG" cDate="03/05/2008 03:50:35 PST Wed" name="Abandonment" ID="2031" xsi:schemaLocation="../schema/frame.xsd" xmlns="http://framenet.icsi.berkeley.edu" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<definition><def-root>An <fex name="Agent">Agent</fex> leaves behind a <fex name="Theme">Theme</fex> effectively rendering it no longer within their control or of the normal security as one's property.
<ex><fex name="Agent">Carolyn</fex> <t>abandoned</t> <fex name="Theme">her car</fex> and jumped on a red double decker bus.</ex>
<ex>Perhaps <fex name="Agent">he</fex> <t>left</t> <fex name="Theme">the key</fex> in the ignition</ex>
<ex><t>Abandonment</t> <fex name="Theme">of a child</fex> is considered to be a serious crime in many jurisdictions.</ex>
</frame>
我在下面的代码中试过这个 - 我只想在 ex.
from helperDef import *
import os
from xml.dom import minidom
for root, dirs, files in os.walk('frame'):
for file in files:
if (file.endswith('.xml')):
xmldoc = minidom.parse(os.path.join(root, file))
if '<ex>' in xmldoc:
line = find_between(xmldoc, '<ex>', '</ex>')
print(line)
clean_line = cleanText(line)
print(clean_line)
错误是 -
TypeError:“文档”类型的参数不可迭代
有什么办法吗?救命!
解决方案
我认为在 python 中解析 xml 的更好方法是使用 xmltodict
你只需要:
import xmltodict
接着:
data = xmltodict.parse(xml)
然后将您的 xml 文件转换为您可以轻松处理的 python dict。在您的情况下,您可以运行一个循环将所有文件转换为 dicts。
推荐阅读
- wordpress - 在 Visual Composer 中使用 [display-posts] 短代码的问题
- php - Wordpress 父子页面菜单 - wp_list_pages 上的类?
- react-native - 当应用程序在本机反应中被杀死时如何调用API?
- c++ - 操纵向量
- amazon-web-services - Amazon S3 存储:可以在私有存储桶中列出公用文件夹吗?
- windows - 如何在 Windows 上运行 Apache Cassandra 3.x
- javascript - 需要帮助简化 javascript for 循环
- string - Typescript const 字符串比较出错
- excel - Excel 工作簿链接
- ssl - 哪些 TLS/SSL 密码套件被认为是弱/强?