2015-06-11 24 views
-1

我有我想要使用Python,它具有類似於以下行來讀取一個CSV:與Python閱讀CSV打破在方括號

10x org il,"["Modiin, Israel"]","["no current price posted"]","["Modiin: no current size posted"]","{ "Python Bootcamp": {"Price: ","["http://www.10x.org.il/"]","[{ "j": 31.9077, "C": 35.0076 }]" 

,但它打破上的第一方括號這樣的:"[{ "j": 31.9077, "C": 35.0076 }]"SyntaxError: invalid syntax

我用下面的Python讀取文件錯誤信息:

import csv 

with open('programming_bootcamps_csv.csv', 'rb') as csvfile: 
    reader = csv.DictReader(csvfile) 
    for row in reader: 
     print(row["campName"]) 

我已經通過了一些文檔閱讀關於爲什麼方括號會打破這一點,並且沒有就什麼問題或如何解決問題得出任何結論。

+0

您是否嘗試過使用csv.reader()而不是DictReader? –

+1

查看代碼突出顯示SO自動應用:其中一個逗號引號圍繞它,反轉了其餘內容的引用狀態。這會造成格式不完整的CSV文件。 – TigerhawkT3

+0

我打開這條線成三引號的字符串和'計數(「「」)''返回27'。檢查文件,確保所有的報價都匹配,等等。 – TigerhawkT3

回答

1

不要手動預處理的數據,除非絕對必要

我已經根據意見重建你的數據如下:

col1,col2,col3,col4,col5,col6,col7 
10x org il,"[""Modiin, Israel""]","[""no current price posted""]","[""Modiin: no current size posted""]","{ ""Python Bootcamp"": {""Price: ","[""http://www.10x.org.il/""]","[{ ""j"": 31.9077, ""C"": 35.0076 }]" 

現在一切正常。

import csv 

with open('data.csv', 'rb') as csvfile: 
    reader = csv.DictReader(csvfile) 
    for row in reader: 
     for key, value in row.items(): 
      print "{}: {}".format(key, value) 

輸出:

col6: ["http://www.10x.org.il/"] 
col7: [{ "j": 31.9077, "C": 35.0076 }] 
col4: ["Modiin: no current size posted"] 
col5: { "Python Bootcamp": {"Price: 
col2: ["Modiin, Israel"] 
col3: ["no current price posted"] 
col1: 10x org il 

它看起來像好奇格式是JSON和CSV的破碎混合物。你的花括號不匹配,沒有一致性。由於它看起來像是自動生成的,我強烈建議在生成該文件的程序中修復上游的數據格式。

但是,如果你不能修復該數據上游然後進一步處理應該是簡單的,可能使用json.loads()或必要時用蠻力。

+0

「由於它看起來像是自動生成的」 - 我認爲它最初是,然後OP認定它是錯誤的並且改變了它。 – TigerhawkT3

+0

確實。數據犯罪。也許原始文件是json? –

+0

誰知道。我認爲這個故事的寓意並不是要破壞你自己的數據(數據犯罪,事實上:))。 – TigerhawkT3

0

而不是使用DictReader的,寫自己的解析器。

def dict_reader(fn, header=None): 
    for line in open(fn): 
     row = [] 
     while line: 
      field,_, line = line.partition(",") 
      while field.startswith('"["') and not field.endswith('"]"'): 
       rest, _, line = line.partition(",") 
       field += rest 
      row.append(field) 
     if header is None: 
      header = row 
      continue 
     yield dict(zip(header, row)) 
+1

這是一個創造困難的可靠方法。返回並生成格式正確的CSV會好得多,而不是試圖用膠帶破壞破損的一個。 – TigerhawkT3

+0

好吧..使用DictWriter把這個函數的輸出重新放回到一個文件中? – mehtunguh

+0

函數的輸入不應該首先打破。這裏的問題是格式不正確的CSV文件。 – TigerhawkT3