我有一個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
我的問題
- 我怎樣才能通過每一行手動循環自動代替?
- 是否有更好的方式來打印編輯結果,如
edit_results
所示? (我打算讓這個腳本做的不僅僅是在將來刪除回報) - 我在做一些多餘的事情,或者我在腳本中寫的東西可以做不同的事情嗎?
示例輸入:
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?我投入了大量的研究時間,找不到任何東西。我也瀏覽了其他一些問題,並且找不到一個喜歡它的人。 – l1thal
你的意思是你用''''替換每個列的'\ n'? – garg10may
不,我做了一個循環,在每個單元格中單獨查找。我手動指定列,就像你在底部的第六行(34,列)中看到的那樣。這使得它通過第34行中的每一列並刪除所有的回報,但是我怎樣才能讓它通過每一行呢? – l1thal