python.xml和.csv文件操作

python.xml和.csv文件操作,python,xml,csv,Python,Xml,Csv,我将.xml文件转换为.csv文件。在.xml文件中有一些值​​从该类型的txtdescripticao列中:后勤、搜索和支持。“因此,当我阅读文件时,pandas将Logistics后面的逗号解释为列分隔符,并向前抛出其余文本。我正在尝试使用以下代码解决此问题: in_file = 'dados_limpos_2018.csv' out_file = 'dados_2018.csv' output = open(out_file, 'w') with open(in_file, 'r') as

我将.xml文件转换为.csv文件。在.xml文件中有一些值​​从该类型的
txtdescripticao
列中:
后勤、搜索和支持。“
因此,当我阅读文件时,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
示例.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>

罗马里奥
15
RJ
领事馆
2018
罗纳尔多
9
RJ
后勤、搜索和支助
2018

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

如果您共享您的xml文件就好了

根据提供的信息

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

在这两种情况下,您都应该在从xml转换为csv时处理此问题。有了csv->csv将很难实现,而且数量将无法预测

编辑1:

我建议使用lxml中的objectify。 别忘了从xml中删除
。 解决方案如下

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

如果您共享您的xml文件,那就太好了

根据提供的信息

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

在这两种情况下,您都应该在从xml转换为csv时处理此问题。有了csv->csv将很难实现,而且数量将无法预测

编辑1:

我建议使用lxml中的objectify。 别忘了从xml中删除
。 解决方案如下

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

我在
txtdescripticao
列中修改了您的函数以处理这些情况

ncols=5
指数=3
in_文件='dados_limpos_2018.csv'
out_文件='dados_2018.csv'
输出=打开(输出文件“w”)
以open(in_文件,'r')作为源:
对于行输入源:
#冒号分割
数据=line.strip().split(',')
#改变第三要素
数据长度=长度(数据)
如果数据长度>ncols:
#连接所有元素
数据[索引]=''.join(数据[索引:索引+1+(数据列-ncols)])
数据[index+1:]=数据[index+1+data\u len-ncols:]
#写专栏
output.write(“,”.join(数据[: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

OBS.:我假设此问题只发生在
txtDecricao
列中。

我修改了您的函数以处理
txtDecricao
列中的这些情况

ncols=5
指数=3
in_文件='dados_limpos_2018.csv'
out_文件='dados_2018.csv'
输出=打开(输出文件“w”)
以open(in_文件,'r')作为源:
对于行输入源:
#冒号分割
数据=line.strip().split(',')
#改变第三要素
数据长度=长度(数据)
如果数据长度>ncols:
#连接所有元素
数据[索引]=''.join(数据[索引:索引+1+(数据列-ncols)])
数据[index+1:]=数据[index+1+data\u len-ncols:]
#写专栏
output.write(“,”.join(数据[: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

OBS.:我假设此问题只发生在
txtDecricao
列中。

为什么“如果len(数据)>5:”?检查行中是否有超过5个逗号分隔的值(列数)。如果出现这种情况,我假设
txtdescripticao
中的值包含逗号,并且在列表
data
中生成5个以上的值。在原始文件中,有28列,带有逗号的一列是8列。我做了替换:你代码中的3代表我代码中的8;4 => 9; 5 => 10; 错误仍然存在。我将代码修复为更一般的情况,现在应该更清楚了。明白了。但是,要合并列名,请键入:txtdescriptioneayearwhy'if len(data)>5:'?检查行中是否有超过5个逗号分隔的值(列数)。如果出现这种情况,我假设
txtdescripticao
中的值包含逗号,并且在列表
data
中生成5个以上的值。在原始文件中,有28列,带有逗号的一列是8列。我做了替换:你代码中的3代表我代码中的8;4 => 9; 5 => 10; 错误仍然存在。我将代码修复为更一般的情况,现在应该更清楚了。明白了。但是,您正在合并列名,键入:txtdescription.xml文件在代码中的读取位置?仅分配.csv文件。还有,熊猫在哪里使用?什么是期望输出?请把你的帖子发给我。确保您发布的内容可以完全运行(包括
import
行),以便在空的Python环境中重现您的问题?仅分配.csv文件。还有,熊猫在哪里使用?什么是期望输出?请把你的帖子发给我。请确保您发布的内容可以完全运行(包括
import
行),以便在空Python环境中重现您的问题。我正在尝试此操作,但出现以下错误:没有这样的子项:名称区分大小写,因此您有子项“名称”