python.xml和.csv文件操作

2024-04-26 19:16:21 发布

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

我将.xml文件转换为.csv文件。在.xml文件中,有一些来自这种类型的txtDescricao列的值:"Logistics, Search and Support."因此,当我读取该文件时,pandas将Logistics后面的逗号解释为列分隔符,并向前抛出其余文本。我正尝试使用以下代码来解决此问题:

in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
    # split by semicolon
        data = line.strip().split(';')             
    # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            item.replace(',', '')
            output.write(''.join(['', item, '',',']))
            # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()

但是,python已经将逗号解释为分隔符,并将其转换为分号。在这里我想知道:有没有什么方法可以在.csv文件中处理这个问题,或者我必须在.xml到.csv的转换中处理这个问题? .cs文件示例

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018

Example.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <dados>
          <despesa>
                  <name>Romario</name>
                  <number>15</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Consultoria</txtDescricao>
                  <year>2018</year>
           </despesa>

           <despesa>
                  <name>Ronaldo</name>
                  <number>9</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Logistics, Search and Support</txtDescricao>
                  <year>2018</year>
           </despesa>
     </dados>
</xml>

注意:原始文件太大,无法在电子表格编辑器中打开。你知道吗


Tags: 文件csvnameinnumberoutputdataxml
2条回答

如果你能共享你的xml文件就好了。你知道吗

根据提供的信息

如果xml文件数据的值为,,请使用不同的分隔符(分号、制表符、空格)来形成csv文件。 或者 只要将,在XML文件中替换为null,然后转换。你知道吗

在这两种情况下,您应该在从xml转换为csv时处理这个问题。有了csv->;csv将很难实现,而且计数将是不可预测的。你知道吗

编辑1:

我建议使用objectifyfromlxml。 别忘了从xml中删除<?xml version="1.0" encoding="UTF-8"?>。 解决方案如下。你知道吗

from lxml import objectify
import csv

file_xml = open('d:\\path\\to\\xml.xml','r')
converted_csv_file = open("converted.csv","w")
xml_string = file_xml.read()
xml_object = objectify.fromstring(xml_string)
csvwriter = csv.writer(converted_csv_file, delimiter=',',lineterminator = '\n')
count = 0
for row in xml_object.dados.despesa:
    if count == 0:
        csvwriter.writerow([row.name.tag,row.number.tag,row.sgUF.tag,row.txtDescricao.tag,row.year.tag])
    csvwriter.writerow([row.name.text,row.number.text,row.sgUF.text,row.txtDescricao.text.replace(',',''),row.year.text])
    count += 1

您可以通过以下方式安装lxml

pip install lxml

我修改了函数来处理txtDescricao列中的那些情况。你知道吗

ncols= 5
index = 3
in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
     for line in source:
         # split by colon
         data = line.strip().split(',')
         # Change third element
         data_len = len(data)
         if  data_len > ncols:
             # Join all elements
             data[index] = ''.join(data[index:index + 1 + (data_len - ncols)])
             data[index + 1:] = data[index + 1 + data_len - ncols:]
         # Write columns
         output.write(','.join(data[:ncols]))
         output.write('\n')
 output.close()

输入文件:

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018

输出文件:

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics Search and Support, 2018

我假设这个问题只发生在txtDecricao列中。你知道吗

相关问题 更多 >