2012-05-12 90 views
0

如何忽略雙引號之間的逗號並刪除不在雙引號之間的逗號?自定義Python CSV分隔符

+2

你的問題很不清楚。如果你提供了一些輸入格式和你想得到的東西,我認爲這會有所幫助。 – zigg

+0

希望你正在使用[一個正確的CSV解析器](http://docs.python.org/library/csv.html),而不是試圖手動解析。 –

+0

邁克爾,這是一個練習,它想要將文本行分析爲csv格式。我結束了使用csv模塊。儘管如此,我仍然對一種解決模塊問題的方法感興趣。 – tijko

回答

3

包括電池 - 只需使用Python自帶的csv module即可。

例子:

import csv 

if __name__ == '__main__': 
    file_path = r"/your/file/path/here.csv" 
    file_handle = open(file_path, "r") 
    csv_handle = csv.reader(file_handle) 
    # Now you can work with the *values* in the csv file. 
+0

我確實使用了csv模塊。謝謝! – tijko

1

只是爲了你的興趣,你可以(大部分)做到這一點使用正則表達式;

mystr = 'No quotes,"Quotes",1.0,42,"String, with, quotes",1,2,3,"",,""' 
import re 
csv_field_regex = re.compile(""" 
(?:^|,)   # Lookbehind for start-of-string, or comma 
(
    "[^"]*"  # If string is quoted: match everything up to next quote 
    | 
    [^,]*  # If string is unquoted: match everything up to the next comma 
) 
(?=$|,)   # Lookahead for end-of-string or comma 
""", re.VERBOSE) 

m = csv_field_regex.findall(mystr) 

>>> pprint.pprint(m) 
['No quotes', 
'"Quotes"', 
'1.0', 
'42', 
'"String, with, quotes"', 
'1', 
'2', 
'3', 
'""', 
'', 
'""'] 

這處理除引號字符串中出現的轉義引號外的所有內容。也可以處理這種情況,但是正則表達式更糟糕;這就是爲什麼我們有csv模塊。

+0

-1應該返回帶引號的字符串,不帶括號引號。此外,這假設用戶負責將輸入文件拆分成行;當數據中出現新行時有點困難。 –

+0

@JohnMachin:如果你用正則表達式解析csv,你就會遇到比這更大的問題。 ;) –

+1

**你**是用正則表達式解析csv的人。我無法想象你爲什麼寫這個答案。 「大部分」==「失敗」。 –