2014-11-21 24 views
-3

我嘗試了一段時間迭代字符串列表並刪除字符串的第一個字,通過追加剩餘的串到另一個列表,這裏就是我寫道:迭代一個字符串列表,並將所有字符串附加到另一個字符串,除了第一個字

from sys import argv 

my_file = argv[1] 
output_list = [] 
count = 1 

with open(my_file) as input_file: 
    for line in input_file.readlines(): 
     while count < len(line.split(' '): 
      ouput_list.append(line.split(' ')[count]) 
      count += 1 
     count = 0 

with open('out_file.txt', 'w') as output_file: 
    for line in output_list: 
     output_file.write(line) 

一切似乎都到位,但我得到一個語法錯誤......我在想什麼?

提前致謝!

+1

至少告訴我們您做了什麼語法錯誤。 – 2014-11-21 14:02:55

+2

你錯過了關閉'len(line.split('')'關閉它,並且在你的rog中你也有其他問題 – 2014-11-21 14:07:02

回答

1

有兩個語法錯誤。首先,有在此行缺少右括號:

while count < len(line.split(' '): 

其次,你在這一行拼錯output_list

ouput_list.append(line.split(' ')[count]) 

除此之外,你的代碼似乎是邏輯上的缺陷,因爲它消除了所有的空格字之間。

如果你的目標是要刪除文件和周圍的空白的第一個字,同時使其他一切完好,這兩條線應該做的伎倆:

text = open(my_file).read() 
text = re.sub('^\s*\w+\s*', '', text) 

它也可以寫成一行,但我更喜歡兩行清晰。

你需要的re模塊,讓你完整的程序是這樣的:

import sys, re 

my_file = sys.argv[1] 

text = open(my_file).read() 
text = re.sub('^\s*\w+\s*', '', text) 

with open('out_file.txt', 'w') as output_file: 
    output_file.write(text) 

如果您使用該輸入文件:

ant bear cat 
dog elephant 

你會得到這樣的輸出:

bear cat 
dog elephant 

我想這就是你想要的。

-1

這是工作代碼: -

from sys import argv 

my_file = argv[1] 
output_list = [] 
count = 1 

with open(my_file) as input_file: 
    for line in input_file.readlines(): 
     while count < len(line.split()): 
      output_list.append(line.split()[count]) 
      count += 1 
     count = 0 

with open('out_file.txt', 'w') as output_file: 
    for line in output_list: 
     output_file.write(line+'\n') # should write in new line 
+0

如果你解釋了你改變了什麼以及爲什麼 – jonrsharpe 2014-11-21 14:18:24

+0

@jonrsharpe感謝(3)你錯過了右括號,正如我在評論中所提到的'len(line.split())'和這裏'ouput_list.append'它的'ouput_list'這個名字是錯誤的,你最好使用split() ('')'並將數據插入新行或空格中,所以'output_file.write(line +'\ n')'或'output_file.write(line +'\ t')' – 2014-11-21 14:22:28

+1

...在答案中。 – jonrsharpe 2014-11-21 14:44:23

相關問題