提取XML文件Python时出现Unicode错误

时间:2016-05-23 19:11:02

标签: python xml unicode

import os, csv, io

from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")

with io.open('test.csv','w', encoding='utf8') as fp:
    a = csv.writer(fp, delimiter=',')
    for f in Fruit:
        Explanation = f.findtext("Explanation")
        Types = f.findall("Type")
        for t in Types:
            Type = t.text
            a.writerow([Type, Explanation])    

我从XML文件中提取数据,并将其放入CSV文件中。我收到以下错误消息。这可能是因为提取的数据包含华氏温度标志。如何在不手动修复XML文件的情况下摆脱这些Unicode错误?

对于我的代码的最后一行,我收到此错误消息 UnicodeEncodeError:'ascii'编解码器无法对位置1267中的字符u'\ xb0'进行编码:序数不在范围内(128)

<Fruits>
<Fruit>
    <Family>Citrus</Family>
    <Explanation>They cannot grow at a temperature below 32 °F</Explanation>
    <Type>Orange</Type>
    <Type>Lemon</Type>
    <Type>Lime</Type>
    <Type>Grapefruit</Type>
</Fruit>
</Fruits>

1 个答案:

答案 0 :(得分:0)

您没有写错误发生的地方。可能在最后一行。你必须自己编码字符串:

template<typename T> Dynamic_Array<T>& Dynamic_Array<T>::operator+=(const T& object) {
    //...
}