使用 python 读取多个目录下的所有 XML 个文件
Read all XML files under multiple directories using python
我正在通过 Jupyter 笔记本使用 Pandas。我有 10 个 XML 个文件,它们存储在多个位置。
例如:
./A/1.xml
./A/2.xml
./A/3.xml
./B/4.xml
./B/5.xml
./B/6.xml
如何加载所有这些文件,以便在每个文件中提取三个特定元素,例如 id、name 和 hypothesis?
我在问题的加载方面需要帮助。仅供参考,如果我对每个文件执行以下操作,则上面使用的路径有效:
from lxml import etree
ltree = etree.parse("./100/A/1.xml")
我更喜欢使用 BeautifulSoup 的解决方案,但是 lxml 或 ElementTree 也很好。
XML 文档的结构是:
<?xml version="1.0" encoding="UTF-8"?>
<pub-ref>
<doc-id>
<country>US</country>
<doc-num>05040672</doc-num>
<date>20090219</date>
</doc-id>
</pub-ref>
<app-ref>
<doc-id>
<country>US</country>
<doc-num>111324</doc-num>
<date>20100919</date>
</doc-id>
</app-ref>
使用 glob
获取与您的模式匹配的所有文件的列表:
import glob
import os
from lxml import etree
dir = '/path/to/the/parent/directory/'
for file in glob.iglob(os.path.join(dir, '*/*.xml')):
with open(file) as f:
data = etree.parse(f)
我正在通过 Jupyter 笔记本使用 Pandas。我有 10 个 XML 个文件,它们存储在多个位置。 例如:
./A/1.xml
./A/2.xml
./A/3.xml
./B/4.xml
./B/5.xml
./B/6.xml
如何加载所有这些文件,以便在每个文件中提取三个特定元素,例如 id、name 和 hypothesis?
我在问题的加载方面需要帮助。仅供参考,如果我对每个文件执行以下操作,则上面使用的路径有效:
from lxml import etree
ltree = etree.parse("./100/A/1.xml")
我更喜欢使用 BeautifulSoup 的解决方案,但是 lxml 或 ElementTree 也很好。
XML 文档的结构是:
<?xml version="1.0" encoding="UTF-8"?>
<pub-ref>
<doc-id>
<country>US</country>
<doc-num>05040672</doc-num>
<date>20090219</date>
</doc-id>
</pub-ref>
<app-ref>
<doc-id>
<country>US</country>
<doc-num>111324</doc-num>
<date>20100919</date>
</doc-id>
</app-ref>
使用 glob
获取与您的模式匹配的所有文件的列表:
import glob
import os
from lxml import etree
dir = '/path/to/the/parent/directory/'
for file in glob.iglob(os.path.join(dir, '*/*.xml')):
with open(file) as f:
data = etree.parse(f)