【问题标题】:reading comma separated value from string object in python从python中的字符串对象读取逗号分隔值
【发布时间】:2015-10-15 10:18:01
【问题描述】:

我有来自 http 请求的输出,它是字符串类型,但数据类似于 csv。因为我的请求标头中的输出类型是 csv ('Accept':"application/csv")。由于这是源支持的格式。但响应内容类型是字符串。 res=request.contenttype(res)` 给了我字符串。

这是对象(res)的示例输出:

QueryTime
start,end
144488,144490

Data

Data - AData
id,G_id,name,type,time,sid,channel
23,-1,"B1",type1,144488,11,CH23
23,-1,"B1",type1,144488,11,CH23
Data - BData
id,G_id,time,se
23,-1,144488,undefined
23,-1,144488,undefined

如果您看到数据是 csv 格式并且有多个表格,例如您看到“AData”和“BData” 我不知道采取哪种方法来阅读本文。我试过 csv 模块但没有帮助。 我尝试过 dict.csv 进行转换,但同样如此。没有得到想要的输出。 可能是我做错了什么,因为我是 python 新手。 需要的是从输出对象中读取每个表。

with open('file.csv', 'wb') as csvfile:
  spamwriter = csv.writer(csvfile, delimiter=',',quoting=csv.QUOTE_NONE)
  spamwriter.writerow(rec)

with open('file.csv') as csvfile:
   reader = csv.DictReader(csvfile)
   for row in reader:
   print row

请高手指导:-)

【问题讨论】:

标签: python python-2.7 csv


【解决方案1】:

您可以使用正则表达式预先解析输出以提取各个部分,然后使用StringIO 将每个部分解析为csv.reader,如下所示:

import csv
import StringIO
from collections import OrderedDict

output = """
QueryTime
start,end
144488,144490

Data

Data - AData
id,G_id,name,type,time,sid,channel
23,-1,"B1",type1,144488,11,CH23
23,-1,"B1",type1,144488,11,CH23
Data - BData
id,G_id,time,se
23,-1,144488,undefined
23,-1,144488,undefined"""

sections = ['QueryTime', 'Data - AData', 'Data - BData', 'Data']
re_sections = '|'.join([re.escape(s) for s in sections])
tables = re.split(r'(' + re_sections + ')', output)
tables = [t.strip() for t in tables[1:]]

d_tables = OrderedDict()

for section, table in zip(*[iter(tables)]*2):
    if len(table):
        csv_input = csv.reader(StringIO.StringIO(table))
        d_tables[section] = list(csv_input)

for section, entries in d_tables.items():
    print section
    print entries
    print

给你以下输出:

QueryTime
[['start', 'end'], ['144488', '144490']]

Data - AData
[['id', 'G_id', 'name', 'type', 'time', 'sid', 'channel'], ['23', '-1', 'B1', 'type1', '144488', '11', 'CH23'], ['23', '-1', 'B1', 'type1', '144488', '11', 'CH23']]

Data - BData
[['id', 'G_id', 'time', 'se'], ['23', '-1', '144488', 'undefined'], ['23', '-1', '144488', 'undefined']]

【讨论】:

    【解决方案2】:

    我想出了这个函数来解析数据:

    def parse_data(data):
     parsed = {}
     current_section = None
    
     for line in data.split('\n'):
      line = line.strip()
      if line:
       if ',' in line:
        current_section.append(line.split(','))
       else:
        parsed[line] = []
        current_section = parsed[line]
     return parsed
    

    它返回一个字典,其中每个键都指向输入的一部分。它的值是一个列表,其中每个成员代表一行输入。每行也是作为字符串的单个值的列表。它不会特别对待节中的第一行。

    在你的输入上运行它会产生这个(为了可读性而重新格式化):

    {
     'Data - AData': [
      ['id', 'G_id', 'name', 'type', 'time', 'sid', 'channel'],
      ['23', '-1', '"B1"', 'type1', '144488', '11', 'CH23'],
      ['23', '-1', '"B1"', 'type1', '144488', '11', 'CH23']
     ],
     'Data - BData': [
      ['id', 'G_id', 'time', 'se'],
      ['23', '-1', '144488', 'undefined'],
      ['23', '-1', '144488', 'undefined']
     ],
     'Data': [
     ],
     'QueryTime': [
      ['start', 'end'],
      ['144488', '144490']
     ]
    }
    

    【讨论】:

    • 得到一个 AttributeError: 'module' 对象没有属性 'split'。我添加了 csv 模块。导入csv
    • 我的函数 parse_data 采用常规字符串 (data)。它不需要任何特殊模块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多