2015-10-05 43 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

相關問題