使用python中的特殊字符将XML转换为csv

问题描述 投票:0回答:1

由于将xml转换为csv的几天而被困住,但我发现它无济于事。我已经尝试过使用带有或不带有特殊字符的脚本,当没有特殊的特殊字符时,它可以完美地工作。特殊字符,iam表示德语字符ü,ß以及所有这些。

import xml.etree.ElementTree as ET
import csv


tree = ET.parse("demoxml.xml")
root = tree.getroot()

f = open('demoxml.csv', 'w', newline='')

csvwriter = csv.writer(f)

count = 0

head = ['Author','Title','Genre','Price','Publish date', 'description']

csvwriter.writerow(head)

for time in root.findall('book'):
    row = []
    Author = time.find('author').text
    row.append(Author)
    Title = time.find('title').text
    row.append(Title)
    Genre = time.find('genre').text
    row.append(Genre)
    Price = time.find('price').text
    row.append(Price)
    Publish = time.find('publish_date').text
    row.append(Publish)
    Description = time.find('description').text
    row.append(Description)
    csvwriter.writerow(row)
f.close()

demo.xml

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Matthew Müller</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Kim Großer</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>

我应该在哪里将decode()或encode('utf-8')放在哪里,我几乎在每个步骤都尝试过,但仍然失败。

python-3.x xml-parsing
1个回答
1
投票

以这种方式尝试,看看是否可行:

替换

import csv

with

import unicodecsv as csv

f = open('demoxml.csv', 'w', newline='')
csvwriter = csv.writer(f)

with

f = open('demoxml.csv', 'wb')
csvwriter = csv.writer(f, dialect='excel', encoding='utf-8')
© www.soinside.com 2019 - 2024. All rights reserved.