-1

方法从给定的 XLS 文件collectInfoFromXLS()中提取所有内容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()

这样我就可以像printinside 方法一样获得每一行,我不想rows2在另一个列表中追加,因为它在检索时会出现问题。

4

1 回答 1

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()返回一个生成器对象而不是一个列表,并且您只能循环该对象一次。

于 2013-10-22T07:34:07.873 回答