7

私はxlrdxlsファイルで作業するために使用しています。私の xls ファイルには 2 つの列があり、両方の列の行数が同じであることを確認する必要があります。から、インデックスで指定された行の長さを探すhelp()必要があることを学びましたが、 を見つけることができません。何かお手伝いできますかrow_len()col_len

これが私のコードです

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
 >>>
4

1 に答える 1

7

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

それが役立つことを願っています。

于 2013-06-05T09:55:11.180 に答える