方法collectInfoFromXLS()
从给定的XLS文件中提取quotes ('')
下的所有内容,并放入List
。
class ExtractInfo(object):
def collectInfoFromXLS():
workbookPath = config.get('TestCaseFileURL','XLSpath')
workbook = xlrd.open_workbook(workbookPath)
SheetPath = config.get('TesCaseSheetName','Sheet1')
worksheet = workbook.sheet_by_name(SheetPath)
numOfRows = worksheet.nrows - 1
curr_row = 0
row1 = []
row2 = []
while curr_row < numOfRows:
curr_row += 1
row2 = []
row = worksheet.row(curr_row)
for value2 in re.findall(r"'(.*?)'", str(row)):
row2.append(value2)
return row2
当我打印row2
时,我得到此方法的输出
['', 'MUC-EC-099_SC-Memory-01_TC-1', 'Description1.', '', '', '', '', '', '', '', '', '', '', '', '']
['', 'MUC-EC-099_SC-Memory-01_TC-2', 'Description2', '', '', '', '', '', '', '', '', '', '', '', '']
......
我想从课外调用此方法,例如
Classobject = ExtractInfo(object)
print Classobject.collectInfoFromXLS()
这样我就可以在方法中获得与print
完全相同的每一行,
我不想在另一个列表中添加rows2
,因为它在检索时会出现问题。
答案 0 :(得分:1)
Python方法一次只能返回一个结果。
一个结果可以是一个列表列表;只返回一个更大的列表,并在结果上循环:
result = []
row2 = []
while curr_row < numOfRows:
curr_row += 1
row2 = []
row = worksheet.row(curr_row)
for value2 in re.findall(r"'(.*?)'", str(row)):
row2.append(value2)
result.append(row2)
return result
和
for row in Classobject.collectInfoFromXLS():
print row
更高级的技术是将您的方法转换为生成器函数,并逐个生成行。你仍然会循环使用该方法。要使函数成为生成器,请使用yield
表达式;一旦将return
作为生成器,就不能再使用def collectInfoFromXLS():
workbookPath = config.get('TestCaseFileURL','XLSpath')
workbook = xlrd.open_workbook(workbookPath)
SheetPath = config.get('TesCaseSheetName','Sheet1')
worksheet = workbook.sheet_by_name(SheetPath)
numOfRows = worksheet.nrows - 1
curr_row = 0
row2 = []
while curr_row < numOfRows:
curr_row += 1
row2 = []
row = worksheet.row(curr_row)
for value2 in re.findall(r"'(.*?)'", str(row)):
row2.append(value2)
yield row2
:
for row in Classobject.collectInfoFromXLS():
print row
你仍然必须循环输出:
Classobject.collectInfoFromXLS()
仅现在{{1}}返回生成器对象而不是列表,并且您只能循环该对象一次。