gpt4 book ai didi

python - 在 pandas 中解析 XML

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:57 26 4
gpt4 key购买 nike

我有一个 xml 文件列表,我想在每个文件中获取两个值来为数据帧创建索引。我使用 for 循环来执行此操作,因为我有大约 1000 个文件,这并不是那么大,并且我想计算这些文件的一些特征以存储在数据帧中。

例如,第一个文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<tag1>
<tag2>
<tag3>
<author>The author</author>
<title> The title </title>
</tag3>
</tag2>
</tag1>

所以我可以使用多索引[author,title]创建一个数据框:

tree = etree.parse(file)
root = tree.getroot()
title = tree.xpath("/tag1/tag2/tag3/author")[0].text
author = tree.xpath("/tag1/tag2/tag3/title")[0].text

features = [Some Feature engineering]
features_names = [List of the feature names]
pd.DataFrame(features,columns = features_names,index = [[author],[title]])

我的问题是,由于文件之间的结构始终相同(相同数量的标签),标签的名称可能会从一个文件更改为另一个文件,例如:

<?xml version="1.0" encoding="utf-8"?>
<tag_1>
<secondtag>
<tag3>
<author>The second author</author>
<title> The second title </title>
</tag3>
</secondtag>
</tag_1>

如何在事先不知道标签名称的情况下访问作者和标题?

最佳答案

关于python - 在 pandas 中解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46949651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com