[英]reading comma separated value from string object in python
我從http請求中獲得了字符串類型的輸出,但是數據就像csv一樣。 由於我的請求標頭中的輸出類型是csv(“接受”:“ application / csv”)。 由於源支持這種格式,但是響應內容類型是字符串。 res=request.content
type(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
專家請指導:-)
您可以使用正則表達式預解析輸出以提取各個部分,然后使用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']]
我想出了這個功能來解析數據:
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']
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.