python - 使用python更改文件格式
问题描述
请帮助我使用 python 将以下 xml 文件转换为 csv 格式。
我得到了一个像下面这样的 xml 文件,格式像 excel。但是,我想将其转换为 csv 格式。
我的原始文件有更多的列和行。每个文件的列数或多或少都不同。我无法在此处粘贴整个代码。但是,这是 xml 中表、行和列的定义。
<Table ss:ExpandedColumnCount="3" ss:ExpandedRowCount="3" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="15">
<Column ss:Width="57.5"/>
<Column ss:Width="49.5"/>
<Row ss:Height="14.5">
<Cell><Data ss:Type="String">Date</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
<Cell><Data ss:Type="String">Time</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
<Cell><Data ss:Type="String">Language</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
</Row>
<Row ss:AutoFitHeight="0">
<Cell ss:StyleID="s62"><Data ss:Type="DateTime">2021-02-15T00:00:00.000</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
<Cell ss:StyleID="s63"><Data ss:Type="DateTime">1899-12-31T22:46:17.000</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
<Cell><Data ss:Type="String">Norwegian</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
</Row>
<Row ss:AutoFitHeight="0">
<Cell ss:StyleID="s62"><Data ss:Type="DateTime">2021-02-15T00:00:00.000</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
<Cell ss:StyleID="s63"><Data ss:Type="DateTime">1899-12-31T22:23:34.000</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
<Cell><Data ss:Type="String">Norwegian</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
</Row>
</Table>
我的预期输出如下:
Date,Time,Language
2/15/2021,22:46,Norwegian
2/15/2021,22:23,Norwegian
解决方案
假设您发布的 XML 是“固定的”,一种方法是使用BeautifulSoup
内置 Pythoncsv
库,如下所示:
from datetime import datetime
from bs4 import BeautifulSoup
import csv
with open('input.xml') as f_xml:
xml = f_xml.read()
soup = BeautifulSoup(xml, "lxml")
with open('output.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(['Date', 'Time', 'Language'])
for row in soup.find_all('row')[1:]:
cells = row.find_all('cell')
date1 = datetime.strptime(cells[0].data.text, '%Y-%m-%dT%H:%M:%S.%f')
date2 = datetime.strptime(cells[1].data.text, '%Y-%m-%dT%H:%M:%S.%f')
language = cells[2].data.text
csv_output.writerow([date1.strftime('%m/%d/%Y'), date2.strftime('%H:%M'), language])
这将使输出为:
Date,Time,Language
02/15/2021,22:46,Norwegian
02/15/2021,22:23,Norwegian
这首先找到所有row
元素,然后提取单元格元素。datetime
对象是从两个日期创建的,允许在输出时调整格式。
推荐阅读
- html - Firefox 不显示内联 pdf
- function - 有没有一种方法可以返回一种可以拥有多个数量的乐趣?
- javascript - 将状态映射到道具返回未定义且不更新
- f# - F# 我可以在数组上使用负索引吗?(就像在 Python 中一样)?
- svnsync - svnsync 与源存储库密码
- c# - 如何使人物面对行进方向?
- android - SQLite:每秒插入 1 个值还是每分钟插入多个值?
- python - 如何对作为完成模型中外键的特定客户端的所有完成求和?
- javascript - 如何使用正则表达式解析名字、姓氏、中间名和后缀
- html - html和html5的基本区别是什么