作家.作家将XML解析为CSV

2024-06-25 23:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

就像我以前的文章一样,我试图解析一个XML文件。文件是:

<?xml version="1.0" ?>

<library>
 <book>
  <title>Sandman Volume 1: Preludes and Nocturnes</title>
  <author>Neil Gaiman</author>
 </book>
 <book>
  <title>Good Omens</title>
  <author>Neil Gamain</author>
  <author>Terry Pratchett</author>
  </book>
 <book>
  <title>All the Lovely Things</title>
  <author>James Daniel Wise</author>
 </book>
 <book>
  <title>Beginning Python</title>
  <author>Peter Norton, et al</author>
 </book>
</library>

我的Python脚本是:

^{pr2}$

这给了我这个输出:

title,author,author
Sandman Volume 1: Preludes and Nocturnes,Neil Gaiman
Good Omens,Neil Gamain,Terry Pratchett
All the Lovely Things,James Daniel Wise
Beginning Python,"Peter Norton, et al"

首先,我想知道它为什么在最后一行“Peter Norton,et al.”加上引号,以及如何摆脱这个问题!在我的代码中添加QUOTE_NONE可以阻止这行代码被返回。在

另外,我想添加另一个列标题'key'。我想用序列号填充这个输出:

key,title,author,author
1,Sandman Volume 1: Preludes and Nocturnes,Neil Gaiman
2,Good Omens,Neil Gamain,Terry Pratchett
3,All the Lovely Things,James Daniel Wise
4,Beginning Python,Peter Norton, et al

我尝试过各种方法,比如设置一个“key”变量=0,然后在def循环中执行key=+1,但这行不通。在


Tags: andkeytitleetpeterauthoralvolume
1条回答
网友
1楼 · 发布于 2024-06-25 23:45:09

首先,试试这个(可能是你期望的程序)。计数器可以从itertools导入以设置为key

from xml.dom.minidom import parse
import xml.dom.minidom
import csv
from itertools import count
c = count(1) #starts from 1
def writeToCSV(myLibrary):
    with open('csvout.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile, delimiter = ',')
        writer.writerow(['key', 'title', 'author', 'author']) #added key
        books = myLibrary.getElementsByTagName("book")
        for book in books:
            titleValue = book.getElementsByTagName("title")[0].childNodes[0].data
            authors =[]
            for author in book.getElementsByTagName("author"):
                authors.append(author.childNodes[0].data) 
            writer.writerow([c.next()] + [titleValue] + authors)

doc = parse('library.xml')
myLibrary = doc.getElementsByTagName("library")[0]

那么为什么quotes around the last line "Peter Norton, et al"?在

因为您使用的是delimeter= ",",所以该名称包含,,所以""是用来在csv file中充当一个{}

相关问题 更多 >