2013-06-04 75 views
5

我使用xlrd來處理xls文件。我的xls文件有兩列,我的要求是確保兩列的行數相等。我從help()得知我們有一個row_len()尋找索引給出的行的長度,但無法找到任何col_len。可以請你任何Python:XLRD;比較列長度

幫助這裏是我的代碼

from xlrd import open_workbook 
spread_sheet=open_workbook("simple.xls") 
sheet1=spread_sheet.sheet_by_index(0) 

#validates the no of columns in the Spread sheet 
if sheet1.ncols == 2: 
    for sheet1_rows in range(sheet1.nrows): 
    for sheet1_cols in range(sheet1.ncols): 
     value=sheet1.cell(sheet1_rows,sheet1_cols).value 
     source=sheet1.cell(sheet1_rows,0).value 
     destination=sheet1.cell(sheet1_rows,1).value 
    #ignores the Source and Destination Headers 
    if value not in ('Source','Destination'): 
     print "Source is : %s \nDestination is : %s\n" % (source,destination) 
else: 
    print "XLS provided is not valid. Check the no of columns is 2" 

一些其他的選擇除了比較下面請

>>> print len(sheet1.col_values(0)) 
8 
>>> print len(sheet1.col_values(1)) 
8 

感謝您的回覆@alecxe。相反,在我的代碼中添加更多行,我發現了下面的一些內容。請告知本會制定出

>>> print len(sheet1.col_values(0)) 
6 
>>> print len(sheet1.col_values(1)) 
6 
>>> sheet1.col_values(0) 
[u'A', 1.0, 1.0, 1.0, 1.0, 2.0] 
>>> sheet1.col_values(1) 
[u'B', 2.0, 2.0, 2.0, 2.0, ''] 
>>> print len(filter(None,sheet1.col_values(1))) 
5 
>>> 
+0

len(sheet1.col_values(0))'有什麼問題? –

+0

感謝您的回覆@MikeMuller。由於我是Python的新手,我正試圖學習所有可以節省工作量的BIF。只是想知道是否有任何存在於Python而不是'len(sheet1.col_values(0))'。 – Sathy

+1

究竟是什麼意思列長?任何地方都可能有空單元。 –

回答

4

不能用於測量許多細胞是如何在列(列長度)設置使用len(sheet.col_values(index))col_values長度始終等於sheet.nrows

想象一下你在input.xls如下:

A B 
1 2 
1 2 
1 2 
1 2 
    2 

然後len(sheet.col_values(0))將返回5(以及len(sheet.col_values(1))),這是不正確。應該是4

相反,它是更好地使用這樣的事情:

from itertools import takewhile 
import xlrd 


def column_len(sheet, index): 
    col_values = sheet.col_values(index) 
    col_len = len(col_values) 
    for _ in takewhile(lambda x: not x, reversed(col_values)): 
     col_len -= 1 
    return col_len 


book = xlrd.open_workbook("input.xls") 
sheet = book.sheet_by_index(0) 

print column_len(sheet, 0) # prints 4 
print column_len(sheet, 1) # prints 5 

希望有所幫助。