2015-10-05 134 views
0

我有一个Python脚本,它读取一个.xls文件并使用一个循环删除每行内部的所有不必要的返回。到目前为止,我的脚本可以通过我指定的行并删除返回,但我希望它能够自动遍历每一行并删除所有不必要的返回。这里是我的脚本 -如何在Python中的循环中迭代多个变量?


import xlrd 
import xlwt 

# function for removing returns in file 
edits_returns = '' 
def remove_returns1(row, column): 
    global edits_returns 
    cell_hold = sheet.cell(row, column).value 
    cell_hold_str = str(cell_hold) 
    if "\n" in cell_hold_str: 
     edits_returns = edits_returns + ('Return(s) replaced in (row %d : cell %d.)\n' % (row, column)) 
    out_cell = cell_hold_str.replace('\n', '') 
    return out_cell 

# obtaining filename 
fname = raw_input('Input Filename > ') 

# opening file 
workbook = xlrd.open_workbook(fname) 
sheet = workbook.sheet_by_index(0) 

# informing user of # of rows and columns 
print "\nNumber of rows: %d" % sheet.nrows 
print "Number of Columns: %d\n" % sheet.ncols 

# removing returns by row 
column = 0 
while column < sheet.ncols: 
    new_value = remove_returns1(34, column) 
    column += 1 
    print new_value, 

# printing the edits 
print "\n\n", edits_returns 

  • 我的问题

    1. 我怎样才能通过每一行手动循环自动代替?
    2. 是否有更好的方式来打印编辑结果,如edit_results所示? (我打算让这个脚本做的不仅仅是在将来删除回报)
    3. 我在做一些多余的事情,或者我在脚本中写的东西可以做不同的事情吗?

示例输入:

10/13/15 mcdonalds\n $20 0.01% 
10/13/15 mcdonalds\n $20 0.01% 

输出示例:

10/13/15 mcdonalds $20 0.01% 
10/13/15 mcdonalds $20 0.01% 
  • 所有的行仍然对自己的线路。他们没有附加。

从提供答案的一个输出例子:

10/13/15 mcdonalds $20 0.01%10/13/15 mcdonalds $20 0.01% 

这似乎接近,但仍然不是我要找的。


在此先感谢!我愿意接受所有建设性的批评。

+1

请告诉我为什么我的问题值得-1?我投入了大量的研究时间,找不到任何东西。我也浏览了其他一些问题,并且找不到一个喜欢它的人。 – l1thal

+0

你的意思是你用''''替换每个列的'\ n'? – garg10may

+0

不,我做了一个循环,在每个单元格中单独查找。我手动指定列,就像你在底部的第六行(34,列)中看到的那样。这使得它通过第34行中的每一列并删除所有的回报,但是我怎样才能让它通过每一行呢? – l1thal

回答

1

更换

# removing returns by row 
column = 0 
while column < sheet.ncols: 
    new_value = remove_returns1(34, column) 
    column += 1 
    print new_value, 

# printing the edits 
print "\n\n", edits_returns 

下面。您需要逐一查看行,然后逐行查看。

# removing returns by row 
row_idx =0 
while row_idx < sheet.nrows: 
    col_idx = 0 
    while col_idx < sheet.ncols: 
     new_value = remove_returns1(row_idx, col_idx) 
     col_idx += 1 
     print new_value, 

    print  
    row_idx += 1 

要将每行存储到一个变量中,您需要先将这些列附加到列表中,然后将它们连接起来。

row_idx =0 
while row_idx < sheet.nrows: 
    col_idx = 0 
    row_data =[] 
    while col_idx < sheet.ncols: 
     new_value = remove_returns1(row_idx, col_idx) 
     col_idx += 1 
     row_data.append(new_value) 

    a= ' '.join(row_data) 
    print a 
    row_idx += 1 

您也可以让“一个”清单,并追加的所有行吧,如果你不希望打印出来或直接使用它们。

+0

无论什么时候在我的代码中都有打印。你看,34是行号。我需要34从0开始,然后一直到.xls文档中的总行数,移除所有的返回值。 – l1thal

+0

我认为它以前也不会工作,您错误地定义了列。以前它是否适用于单行? – garg10may

+0

是的,使用上面提供的原始脚本,可以使用单行。一行是单元格(0-9,0)(零到九)。起初,我认为它是如何设置的,因为行是水平的,但是在单元格的第二部分(列,行)是令人困惑的。我习惯了x/y轴,所以起初我认为它是倒退的(行,列)。所以我确信我已经正确地指定了它。 – l1thal