【发布时间】:2019-05-30 13:15:43
【问题描述】:
我将 .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
.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>
注意:原始文件太大,无法在电子表格编辑器中打开。
【问题讨论】:
-
你的 .xml 文件在哪里读入代码?仅分配 .csv 文件。另外,熊猫在哪里使用?期望的输出是什么?请edit您的帖子为minimal reproducible example。确保您发布的内容可以完全运行(包括
import行)以在空 Python 环境中重现您的问题。