2012-08-27 14 views
-2

我正在逐行讀取一個CSV文件行這裏:閱讀與Python中的CSV和處理空

def GetDistinctValues(theFile, theColumn): 
    lines=theFile.split('\n') 
    allValues=[] 
    for line in lines: 
    if line: 
     distinctValue=line.split(',')[theColumn] 
     allValues.append(distinctValue)   
    return list(set(allValues)) 

,這裏是我的csv是什麼樣子:

1,hat,dog 
2,,cat 
3,pants,elephant 
4,,, 

,你可以看到,有時有空白。

在上面的代碼中,我試圖獲取特定列中的所有唯一值,但這不起作用,因爲列轉移有時是因爲它沒有考慮到空白。

如何解釋所有空白並獲得特定列中的所有不同值?

+8

你聽說過嗎? http://docs.python.org/library/csv.html –

+0

@FlorinStingaciu看起來不錯!我將如何從列中使用它獲得不同的值? –

+0

@АртёмЦарионов請參閱示例部分:http://docs.python.org/library/csv.html#examples您可以使用'[]'運算符訪問該行 – devsnd

回答

3

也許是這樣的:

import csv 

def get_distinct_values(filename, column): 
    with open(filename, "rb") as fp: 
     reader = csv.reader(fp) 
     return set(line[column] for line in reader) 

這給

>>> get_distinct_values("ccol.csv", 0) 
set(['1', '3', '2', '4']) 
>>> get_distinct_values("ccol.csv", 1) 
set(['', 'hat', 'pants']) 
>>> get_distinct_values("ccol.csv", 2) 
set(['', 'elephant', 'dog', 'cat']) 

如果您想擺脫空值,您可以使用set(line[column] for line in reader if line[column])或其他東西。

+0

打開(theFile,「rb」)爲fp: TypeError:強制轉換爲Unicode:需要字符串或緩衝區,找到_csv.reader –

+0

當使用'with open(something)'時,「something」通常應該是文件名。你的錯誤消息使你看起來像是通過了別的東西,一個csv.reader。 – DSM

2

這將讓你開始:

import csv 
csvf=csv.reader(open(yourfile,'rb')) 

col=0 
rtr=set() 
for row in csvf: 
    rtr.add(row[col]) 

print rtr  

在你的榜樣,打印:

set(['1', '3', '2', '4'])