这是我的代码,我用它打开excel表,然后将每行作为字符串列表返回(其中每个单元格都是一个字符串)。该类返回一个列表,该列表填充了与文件中的行一样多的列表。所以50行将返回50个列表。
from xlrd import open_workbook
class ExcelReadLines(object):
def __init__(self,path_to_file):
'''Accepts the Excel File'''
self.path_to_file = path_to_file
self.__work__()
def __work__(self):
self.full_file_as_read_lines = []
self.book = open_workbook(self.path_to_file)
self.sheet = self.book.sheet_by_index(0)
for row_index in range(self.sheet.nrows):
single_read_lines = []
for col_index in range(self.sheet.ncols):
cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
cell_value_stripped = cell_value_as_string.strip('u')
single_read_lines.append(cell_value_stripped)
self.full_file_as_read_lines.append(single_read_lines)
return self.full_file_as_read_lines
但是当我跑步时:
for x in ExcelReader('excel_sheet'): print x
我收到错误消息:
class is not iterable
答案 0 :(得分:7)
为了使一个类可迭代,它需要一个__iter__
方法。
考虑:
class Foo(object):
def __init__(self,lst):
self.lst = lst
def __iter__(self):
return iter(self.lst)
示例:
>>> class Foo(object):
... def __init__(self,lst):
... self.lst = lst
... def __iter__(self):
... return iter(self.lst)
...
>>> Foo([1,2,3])
<__main__.Foo object at 0xe9890>
>>> for x in Foo([1,2,3]): print x
...
1
2
3
你的例子看起来好像作为一个发电机会好一点 - 我真的不明白这里的课程需要什么:
def excel_reader(path_to_file):
book = open_workbook(path_to_file)
sheet = book.sheet_by_index(0)
for row_index in range(sheet.nrows):
single_read_lines = []
for col_index in range(sheet.ncols):
cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
cell_value_stripped = cell_value_as_string.strip('u')
single_read_lines.append(cell_value_stripped)
yield single_read_lines
答案 1 :(得分:2)
您应该考虑实现Python的special iterator methods。
另外,请注意,您不应该为方法__work__
命名,因为它使用魔术方法语法,但实际上并不是真正的魔术方法。
答案 2 :(得分:1)
这里有一些问题。
您的代码不会返回任何内容。您拨打__work__
但不返回该值。
即使它确实如此,那也无济于事,因为从__init__
返回某些内容并不会使该对象成为那样。
你不希望你的对象 一个列表,你只想迭代它。
有关如何在Python中编写迭代器的简单示例,请参阅this question。
此外,您不应在代码中使用双下划线三明治名称,例如__work__
。这种名称按照惯例保留给Python内部使用。
答案 3 :(得分:0)
除非我弄错了,你真正想要的是
def first_sheet(fname):
wb = xlrd.open_workbook(fname)
ws = wb.sheet_by_index(0)
for i in xrange(ws.nrows):
yield ws.row_values(i) # maybe strip 'u''s - but that looks a bit sus... (probably something to do with your `str`)
list_of_rows = list(first_sheet('somefile.xls'))
如果需要,请使用zip
进行任何转置......