Python脚本不把整行放入Excel电子表格

我有一个Python脚本,拉下HTML,剥离我想要的部分,并给我一个部分看起来像这样的列表:

... San Onofre SB Otay Mesa Platteville NB Platteville SB ... 

脚本的最后一部分将所有这些行放入Excel电子表格的自己的行中。 这段代码看起来像这样:

 print "Now let's put it in a spreadsheet..." time.sleep(1) f = open('Out.txt', 'r+') #The file that's created earlier in the script with the list row_list = [] for row in f: row_list.append(row.split()) column_list = zip(*row_list) rb = open_workbook("CVO.xls",formatting_info=True) r_sheet = rb.sheet_by_index(0) wb = copy(rb) w_sheet = wb.get_sheet(0) i = 2 for column in column_list: for item in range(len(column)): w_sheet.write(item, i, column[item]) wb.save('CVO.xls') i+=1 f.close() os.remove("Out.txt") print "Success!" time.sleep(2) 

结果看起来部分是这样的:

 ... San Otay Platteville Platteville ... 

我认为由于行被拆分的方式,部分被排除在外,但我不知道如何使其包含整个行。

有任何想法吗?

谢谢!!

编辑

我们的目标是将整条生产线(San Onofre SB,Otay Mesa等)列入自己的行列。 现在这样做,除了第一个字之外,它只是一声不响(把San Onofre SB变成了San)。

对困惑感到抱歉。

你的问题是你的zipzip截断到最短的迭代,例如:

 >>> zip(*[[1, 2, 3], [4, 5], [6, 7, 8]]) [(1, 4, 6), (2, 5, 7)] 

幸运的是,你不需要zip ,我不知道你为什么要这样做。 要将每个单词写入单独的列,只需遍历row_list结构即可:

 col_offset = 2 for (rownum, words) in enumerate(row_list): for (colnum, word) in enumerate(words): w_sheet.write(rownum, colnum + col_offset, word) 

enumerateinput迭代器中每个元素的yield (index, pair)值,以便自动遍历序列。 col_offset是因为enumerate是0索引,你的示例代码显示i=2设置起始列。

如果你不想在单独的列中的单词,不要分割线 – 只是strip()他们摆脱新行。 如果必须将它们拆分为以前的处理,请使用join()重新组合它们:

 colnum = 2 for (rownum, words) in enumerate(row_list): w_sheet.write(rownum, colnum, ' '.join(words))