lxml:在csv格式的列表中循环时创建多个标记

ni65a41a  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(142)

我有这样一个csv文件:

customer, restaurant, drink, dish 
1, MC, "C1, C6", "D1, D2, D3"

我想用Python lxml模块得到这样的XML:

<Example>
<Customer> 1 </Customer>
<Restaurant> MC </Restaurant>
<Drink>
   <Drink> C1 </Drink>
   <Drink> C6 </Drink>
</Drink>
<Dish> D1 </Dish>
<Dish> D2 </Dish>
<Dish> D3 </Dish>
</Example>

我目前尝试的是:

import csv
import lxml.etree
from lxml import etree as ET
from lxml.builder import E

with open(r'restaurant.csv') as csvfile:
     result = E.Example(*
                         ( E.Customer(row['customer']),
                           E.Restaurant([row'restaurant']),
                           E.Drink(row['drink']),
                           E.Dish(row['dish']))

     for row in csv.DictReader(csv))
)

tree = lxml.etree.tostring(results, pretty_print=True )

with open(r'output.xml', 'wb') as f:
    f.write(tree)

我不知道如何在另一个循环中循环这个列表。

cvxl0en2

cvxl0en21#

您可以尝试:

import csv
import lxml.etree
from lxml import etree as ET
from lxml.builder import E

with open('data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)

    example = E.Example()

    for row in reader:
        example.append(E.Customer(row['customer']))
        example.append(E.Restaurant(row['restaurant']))
        drink = E.Drink()
        example.append(drink)
        for d in map(str.strip, row['drink'].split(',')):
            drink.append(E.Drink(d))
        for d in map(str.strip, row['dish'].split(',')):
            example.append(E.Dish(d))

tree = lxml.etree.tostring(example, pretty_print=True)
print(tree.decode('utf-8'))

图纸:

<Example>
  <Customer>1</Customer>
  <Restaurant>MC</Restaurant>
  <Drink>
    <Drink>C1</Drink>
    <Drink>C6</Drink>
  </Drink>
  <Dish>D1</Dish>
  <Dish>D2</Dish>
  <Dish>D3</Dish>
</Example>

data.csv的含量:

customer,restaurant,drink,dish
1,MC,"C1, C6","D1, D2, D3"

相关问题