你輸入的字符串是不是真的CSV。相反,您的輸入包含每一行中的列名稱。如果您的輸入如下所示:
NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx
NAME: "2802 wroomer", DESCR: "2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx
NAME: "2803 foobars", DESCR: "2803 foobars, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx
您可以做的最簡單的操作可能是首先在整個文件中過濾掉列名。這會給你一個你可以解析的CSV文件。但是,假定每行都有相同順序的相同列。
但是,如果數據不一致,您可能需要根據名稱進行解析。也許它看起來像這樣:
NAME: "2801 chassis", PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx, DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0"
NAME: "2802 wroomer", DESCR: "2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx
NAME: "2803 foobars", VID: V03 ,PID: CISCO2801 ,SN: xxxxxxxxx
或者什麼。在這種情況下,我會通過查找第一個':'來解析每一行,從中分出列頭,然後解析該值(包括查找引號),然後繼續行的其餘部分。像這樣(完全未經測試的代碼):
def parseline(line):
result = {}
while ':' in line:
column, rest = line.split(':',1)
column = column.strip()
rest = rest.strip()
if rest[0] in ('"', '"'): # It's quoted.
quotechar = rest[0]
end = rest.find(quotechar, 1) # Find the end of the quote
value = rest[1:end]
end = rest.find(',', end) # Find the next comma
else: #Not quoted, just find the next comma:
end = rest.find(',', 1) # Find the end of the value
value = rest[0:end]
result[column] = value
line = rest[end+1:]
line.strip()
return result
請提供一個真實的數據示例 - 它似乎是您的數據不是csv。 – nosklo 2009-10-14 13:52:09