2016-03-06 85 views
5

有沒有辦法,我可以解析一個逗號分隔的字符串,而不使用像csv.reader(..)一樣的花哨?我可以使用split(',')函數,但在有效列值本身包含逗號時不起作用。 csv庫有解析正確處理上述特例的CSV文件的讀者,但是我不能使用這些文件,因爲我需要解析一個字符串。但是,如果Python CSV允許解析單個字符串本身,那麼這對我來說是新聞。解析一個CSV字符串?

回答

11

以在文檔中的csv模塊, 說,仔細一看:

reader(...) 
    csv_reader = reader(iterable [, dialect='excel'] 
          [optional keyword args]) 
     for row in csv_reader: 
      process(row) 

    The "iterable" argument can be any object that returns a line 
    of input for each iteration, such as a file object or a list. The 
    optional "dialect" parameter is discussed below. The function 
    also accepts optional keyword arguments which override settings 
    provided by the dialect. 

所以,如果你有字符串:

>>> s = '"this is", "a test", "of the csv", "parser"' 

而且你想「一個對象返回一行每個 迭代」的輸入,你可以包裝你的字符串列表:

>>> r = csv.reader([s]) 
>>> list(r) 
[['this is', 'a test', 'of the csv parser']] 

這就是你如何分析與csv模塊的字符串。

+0

我想它會更優雅'iter(s)'作爲一般迭代器而不是'[s]'(指定一個列表)。但是你有我的+1 – RafaelC

+0

如果字符串在值的內部引用了換行符,這可能不會起作用; @ alecxe的答案更有意義 – swooby

9

您仍然可以使用csv解析單個字符串。使用StringIO的寫一個字符串buffer(也稱爲內存中的文件):

import csv 
from StringIO import StringIO 

s = "your string" 
buff = StringIO(s) 

reader = csv.reader(buff) 
for line in reader: 
    print(line) 
+0

對於Python 3,使用'from io import StringIO'請參閱[這裏](https://docs.python.org/3/library/io.html#text-io) –