2013-06-04 17 views
5

xls dosyaları üzerinde çalışmak için xlrd kullanıyorum. Benim xls dosyamda iki sütun var ve benim ihtiyacımın iki sütunun da eşit sayıda satıra sahip olduğundan emin olmak. help()'dan, row_len() dizinine sahip olduğumuzu, indeksle verilen bir satırın uzunluğunu aradığımızı, ancak col_len için bulamadıklarını öğrendim. Eğer herhangi birPython: XLRD; sütun uzunluklarını karşılaştırın

ile yardım edebilir İşte

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" 

Bazı diğer seçenekler ayrı cevabınızı @alecxe için aşağıya lütfen

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

Teşekkür karşılaştırarak benim kodudur. Koduma birkaç satır daha eklemek yerine, aşağıda bir şeyler buldum. Birçok hücre sütun (sütun uzunluğu) nasıl ayarlandığını ölçmek için len(sheet.col_values(index)) kullanamazsınız Bu

>>> 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)) 'ile ilgili sorun nedir? –

+0

Cevabınız @MikeMuller için teşekkürler. Python'a yeni başlayan biri olduğum için, bu çabadan tasarruf eden tüm BIF'leri öğrenmeye çalışıyorum. Sadece, Python'da var olanların, len (sheet1.col_values ​​(0)) 'ın dışında olup olmadığını bilmek ilginç. – Sathy

+1

Tam olarak sütun uzunluğu ile ne demek istiyorsunuz? Her yerde boş hücre olabilir. –

cevap

4

hazırlayacağız bildiriniz. col_values uzunluğu her zaman sheet.nrows'a eşittir.

input.xls aşağıdaki sahip düşünün:
A B 
1 2 
1 2 
1 2 
1 2 
    2 

Sonra len(sheet.col_values(0)) yanlış olan ( len(sheet.col_values(1)) yanı sıra) 5 dönecektir. yardımcı olur

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 

Hope: Yerine 4.

olmalı, böyle bir şeyi kullanmak daha iyidir.

İlgili konular