首页 > 解决方案 > 使用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

标签: pythonxmlcsv

解决方案


假设您发布的 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对象是从两个日期创建的,允许在输出时调整格式。


推荐阅读