【问题标题】:Handle comma (,) when converting XML string from string to csv using python使用python将XML字符串从字符串转换为csv时处理逗号(,)
【发布时间】:2021-03-16 18:49:19
【问题描述】:

我需要将 xml 从字符串转换为 csv 并在控制台中打印。我的记录分隔符是 csv 的逗号 (,)。如果逗号出现在 csv 中,那么我必须在检索时为每个 xml 字段加上双引号来处理它。 代码如下。

from xml.etree.ElementTree import XML

input_xml = """<val><policies>
    <policy>
        <policyId>995932</policyId>
        <statecode>FL,FT</statecode>
        <eq_site_limit>CLAY COUNTY</eq_site_limit>
        <hu_site_limit>0</hu_site_limit>
        <fl_site_limit>19260000</fl_site_limit>
        <fr_site_limit>0</fr_site_limit>
        <tiv_2011>0</tiv_2011>
        <tiv_2012>19260000</tiv_2012>
        <eq_site_deductible>20610000</eq_site_deductible>
        <hu_site_deductible>0</hu_site_deductible>
        <fl_site_deductible>0</fl_site_deductible>
        <fr_site_deductible>0</fr_site_deductible>
        <point_latitude>0</point_latitude>
        <point_longitude>30.102226</point_longitude>
        <line>-81.713882</line>
        <construction>Commercial</construction>
        <point_granularity>Reinforced Concrete</point_granularity>
    </policy>
    <policy>
        <policyId>223488</policyId>
        <statecode>FL</statecode>
        <eq_site_limit>CLAY COUNTY</eq_site_limit>
        <hu_site_limit>328500</hu_site_limit>
        <fl_site_limit>328500</fl_site_limit>
        <fr_site_limit>328500</fr_site_limit>
        <tiv_2011>328500</tiv_2011>
        <tiv_2012>328500</tiv_2012>
        <eq_site_deductible>348374.25</eq_site_deductible>
        <hu_site_deductible>0</hu_site_deductible>
        <fl_site_deductible>16425</fl_site_deductible>
        <fr_site_deductible>0</fr_site_deductible>
        <point_latitude>0</point_latitude>
        <point_longitude>30.102217</point_longitude>
        <line>-81.707146</line>
        <construction>Residential</construction>
        <point_granularity>Wood</point_granularity>
    </policy>
</policies></val>"""

root = XML(input_xml)
parsed = root.find('policies')
# print(parsed)

data = []

for policy in parsed:
    policyId = policy.find('policyId').text
    statecode = policy.find('statecode').text
    eq_site_limit = policy.find('eq_site_limit').text
    hu_site_limit = policy.find('hu_site_limit').text
    fl_site_limit = policy.find('fl_site_limit').text
    fr_site_limit = policy.find('fr_site_limit').text
    tiv_2011 = policy.find('tiv_2011').text
    tiv_2012 = policy.find('tiv_2012').text
    eq_site_deductible = policy.find('eq_site_deductible').text
    hu_site_deductible = policy.find('hu_site_deductible').text
    fl_site_deductible = policy.find('fl_site_deductible').text
    fr_site_deductible = policy.find('fr_site_deductible').text
    point_latitude = policy.find('point_latitude').text
    point_longitude = policy.find('point_longitude').text
    line = policy.find('line').text
    construction = policy.find('construction').text
    point_granularity = policy.find('point_granularity').text

    data.append(
        '"{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}"'.format(policyId, statecode, eq_site_limit,hu_site_limit, fl_site_limit,fr_site_limit, tiv_2011, tiv_2012,eq_site_deductible,hu_site_deductible,fl_site_deductible,fr_site_deductible, point_latitude,point_longitude, line, construction,point_granularity))

print('\n'.join([row for row in data[0:]]))

输出如下:

"995932", "FL,FT", "CLAY COUNTY", "0", "19260000", "0", "0", "19260000", "20610000", "0", "0", "0", "0", "30.102226", "-81.713882", "Commercial", "Reinforced Concrete"
"223488", "FL", "CLAY COUNTY", "328500", "328500", "328500", "328500", "328500", "348374.25", "0", "16425", "0", "0", "30.102217", "-81.707146", "Residential", "Wood"

除了"FL,FT" 值之外,如果它们没有逗号值,我想从其他人那里删除双引号。 xml 可能包含也可能不包含逗号值作为字段值。因此,如果逗号值存在,我只想为该记录添加双引号(“”)。

预期输出:

 995932, "FL,FT", CLAY COUNTY, 0, 19260000, 0, 0, 19260000, 20610000, 0, 0, 0, 0, 30.102226, -81.713882, Commercial, Reinforced Concrete

谢谢

【问题讨论】:

  • 你为什么不使用csv.writer
  • @Justin Ezequiel 我使用的是第 3 方工具,无法直接写入 csv 文件。实际上我得到的是 xml 文件作为字符串,我将再次使用它创建一个 csv 作为字符串。
  • 您始终可以使用buffer = io.StringIO(); writer = csv.writer(buffer),它会为您提供类似文件的对象,而不是实际的文件对象。见docs.python.org/3/library/io.html#io.StringIO
  • buffer.getvalue() 会给你字符串。

标签: python xml csv


【解决方案1】:

一个好的 CSV 库应该会为您处理这些问题。您不需要自己构建 CSV。只需确保您在 Python 中的数据正确无误。这是一个例子:

import csv
    
data = ["a", "c,d", "e,f,g"]   # Just make sure you have data like this
with open('file.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(data)

如果您无法写入文件但想要一个字符串,请使用StringIO

import csv
import io
output = io.StringIO()

data = ["a", "c,d", "e,f,g"]   # Just make sure you have data like this
writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(data)
string = output.getvalue()

【讨论】:

  • 这对我有帮助。谢谢+1
猜你喜欢
  • 2018-02-22
  • 1970-01-01
  • 2019-11-18
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 2010-09-09
相关资源
最近更新 更多