从Python中的字符串对象读取逗号分隔的值

D14

我从http请求中获得了字符串类型的输出,但是数据就像csv一样。由于我的请求标头中的输出类型是csv('Accept':“ application / csv”)。源支持的格式是这种格式,但是响应内容类型是字符串。res=request.contenttype(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

专家请指导:-)

马丁·埃文斯(Martin Evans)

您可以使用正则表达式预解析输出以提取各个部分,然后使用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']]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章