简体   繁体   English

在CSV文件中,每个字母都有自己的列

[英]In CSV file each letter has its own column

<Fruits>
<Fruit>
    <Family>Citrus</Family>
    <Explanation>They belong to the Citrus.</Explanation>
    <Type>Orange</Type>
    <Type>Lemon</Type>
    <Type>Lime</Type>
    <Type>Grapefruit</Type>
</Fruit>
<Fruit>
    <Family>Pomes</Family>
    <Explanation>it belongs to the Pomes. Pomes are composed of one or more carpels, surrounded by accessory tissue.</Explanation>
    <Type>Apple</Type>
    <Type>Pear</Type>        
</Fruit>

I want to extract the Explanation of this XML code above, and assign it to each fruit(Type) next to it in a CSV file. 我想提取上述XML代码的解释,并将其分配给CSV文件中它旁边的每个fruit(Type)。 Here is my code below. 这是下面的代码。

import os, csv

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 open('test.csv','w') as fp:
    a = csv.writer(fp, delimiter=',')
    for f in Fruit:
        Explanation = f.find("Explanation").text
        Types = f.findall("Type")
        for t in Types:
            Type = t.text
            print ("{0}, {1}".format(Type, Explanation))
            a.writerows("{0}, {1}".format(Type, Explanation))

For the print statement it appears exactly the way I want it. 对于打印语句,它的显示方式完全符合我的要求。

Orange, They belong to the Citrus family.
Lemon, They belong to the Lemon family. 

and so on... 等等...

However, in the CSV file each letter has its own column. 但是,在CSV文件中,每个字母都有其自己的列。 I would like to have the type in the first column in the CSV file and in the second column the Explanation. 我想在CSV文件的第一列中使用类型,在第二列中使用“说明”。

Column1    Column2
Orange     They belong to the Citrus family.
Lemon      They belong to the Citrus family.

You should use writerow , not writerows . 您应该使用writerow而不是writerows And you should pass it a list, not a string. 您应该向它传递一个列表,而不是字符串。

a.writerow([Type, Explanation])

In my (very limited) experience, I have found that for writing to CSVs, you have to put the desired text for the cells in separate square brackets, for example: 根据我的经验(非常有限),我发现要写入CSV,必须将单元格所需的文本放在单独的方括号中,例如:

a.writerow([Type]+[Explanation])

So it should appear in the CSV as: 因此,它应该在CSV中显示为:

Column 1  Column 2
Type      Explanation

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM