【问题标题】:How to split csv rows containing multiple string values based on comma but without considering comma inside curly brackets { }如何根据逗号拆分包含多个字符串值的csv行,但不考虑大括号{}内的逗号
【发布时间】:2020-01-03 13:33:14
【问题描述】:

我正在读取一个 csv 文件并尝试根据逗号拆分其行,在我的例子中,行包含一些以逗号作为该值的一部分的值,并且该值以 { } 开头和结尾。

我的拆分功能:

    def process(self, row):
        """
        Splits each row on commas
        """
        Uid, controlNo, profileType, LAStpointDetail, LastPointDate = 
                                                         row.split(",")

我的行示例:

0923,41003,Permanent,{""Details"": [{""data"": {""status"": ""FAILURE"", ""id"": ""12345""}, ""DetailType"": ""Existing""}]},2019-06-27

在行中如果您看到“LAStpointDetail”,它已经包含多个逗号。如何根据逗号分割整行。

【问题讨论】:

    标签: python json python-2.7 csv


    【解决方案1】:

    您在这里似乎拥有的是csv 数据,其中一列被编码为json

    无法准确判断问题中的数据是如何引用的(最好粘贴行的repr),但我们假设它是这样的:

    '"0923","41003","Permanent","{""Details"": [{""data"": {""status"": ""FAILURE"", ""id"": ""12345""}, ""DetailType"": ""Existing""}]}","2019-06-27"' 
    

    如果是这样,并且你有一个包含多行数据的文件,你可以使用 csv 模块来读取它:

    import csv
    import json
    with open('myfile.csv', 'rb') as f:
        reader = csv.reader(f)
        # Remove the next line if the first row is not the headers.
        # next(reader)    # Skip header row.
        for row in reader:
            Uid, controlNo, profileType, LAStpointDetail, LastPointDate = row
            # Load embedded json into a dictionary.
            detail_dict = json.loads(LAStpointDetail)
            # Do something with these values.
    

    如果你只有一行作为字符串,你仍然可以使用 csv 模块:

    >>> row = '"0923","41003","Permanent","{""Details"": [{""data"": {""status"": ""FAILURE"", ""id"": ""12345""}, ""DetailType"": ""Existing""}]}","2019-06-27"'
    >>> # Make the data an element in a list ([]).
    >>> reader = csv.reader([row])
    >>> Uid, controlNo, profileType, LAStpointDetail, LastPointDate = next(reader)
    >>> print Uid
    0923
    >>> d = json.loads(LAStpointDetail)
    >>> d
    {u'Details': [{u'DetailType': u'Existing', u'data': {u'status': u'FAILURE', u'id': u'12345'}}]}
    >>> print d['Details'][0]['data']['status']
    FAILURE
    

    【讨论】:

      猜你喜欢
      • 2016-04-12
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多