[英]Ho to parse xml file to xlsx in python
I have a file xml like this (input):我有一个这样的文件 xml(输入):
> <?xml version="1.0" encoding="UTF-8" standalone="yes"?\>
> <obs id="0"\>
> <dim name="Column1" value="a"/\>
> <dim name="Column2" value="b"/\>
> </obs\>
> <obs id="1">
> <dim name="Column1" value="tr"/\>
> <dim name="Column2" value="yu"/\>
> </obs\>
How can i do for parse in xlsx file?我该怎么做才能在 xlsx 文件中进行解析? i would like to have a xlsx file like this:
我想要一个这样的 xlsx 文件:
Column1|Column2 a |b tr |yu列 1|列 2 a |b tr |yu
Column1![]() |
Column2![]() |
---|---|
a![]() |
b ![]() |
tr![]() |
yu![]() |
Thanks a lot.非常感谢。 I've tried with other xml parser but i did not realised the solution.
我试过其他 xml 解析器,但我没有意识到解决方案。
You can use BeautifulSoup
to parse the XML document + pandas
to save the dataframe to CSV and/or Excel format:您可以使用
BeautifulSoup
解析 XML 文档 + pandas
以将数据框保存为 CSV 和/或 Excel 格式:
import pandas as pd
from bs4 import BeautifulSoup
with open("your_file.xml", "r") as f_in:
soup = BeautifulSoup(f_in.read(), "html.parser") # <-- you can ignore the warning or use different parser, such as `xml`
all_data = []
for obs in soup.select("obs"):
d = {}
for dim in obs.select("dim[name][value]"):
d[dim["name"]] = dim["value"]
all_data.append(d)
df = pd.DataFrame(all_data)
print(df)
df.to_csv('data.csv', index=False)
This prints:这打印:
Column1 Column2
0 a b
1 tr yu
and saves data.csv
.并保存
data.csv
。
Input file was:输入文件是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<obs id="0">
<dim name="Column1" value="a" />
<dim name="Column2" value="b" />
</obs>
<obs id="1">
<dim name="Column1" value="tr" />
<dim name="Column2" value="yu" />
</obs>
You need a well formed XML with only one root element
, like:您需要一个只有一个
root element
的格式良好的 XML,例如:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<obs id="0">
<dim name="Column1" value="a"/>
<dim name="Column2" value="b"/>
</obs>
<obs id="1">
<dim name="Column1" value="tr"/>
<dim name="Column2" value="yu"/>
</obs>
</root>
You can parse this xml to columns and rows for a pandas DataFrame and write this df to a Excel sheet with pandas ExcelWriter()
:您可以将此 xml 解析为 pandas DataFrame的列和行,并使用 pandas
ExcelWriter()
将此df写入 Excel 工作表:
import xml.etree.ElementTree as ET
import pandas as pd
import openpyxl
tree = ET.parse('Excel.xml')
root = tree.getroot()
columns = []
data = []
for elem in root.iter('dim'):
if elem.get('name') not in columns:
columns.append(elem.get('name'))
if elem.get('name') == "Column1":
c1 = elem.get('value')
else:
c2 = elem.get('value')
row = (c1, c2)
data.append(row)
df = pd.DataFrame(data, columns=columns)
print(df)
with pd.ExcelWriter("Excel.xlsx") as writer:
df.to_excel(writer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.