2013-08-20 101 views
2

我是編程新手,正在玩Python腳本。如何在Python中結束for循環?

我想寫一個Python腳本,它將讀取文本文件並打印到屏幕上,搜索一個單詞,並且每次找到該單詞時,都會拆分該行的數據。

test.txt文件看起來像:

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar 

我想在屏幕上的最終結果是這樣的:

ape bear cat dog 
ape elephant frog giraffe 
ape horse iguana jaguar 

到目前爲止我的代碼:

file = "test.txt" 
read_file = open(file, "r") 
with read_file as data: 
    read_file.read() 
    print(data) 
    word = "ape" 
    for word in data: 
     data.split() 
     print(data) 

我將該文件作爲變量,因爲我打算在腳本中多次使用它。

當我測試代碼時,for循環在一次循環後沒有停止。它最終結束了,但我確定它是否是代碼或程序自動結束無限循環。

如何編輯代碼以便for循環一旦到達文件末尾就會停止? 是否有更正確的方式來編寫此代碼?

再次,這只是一個示例文件,而不是我的實際文件。 謝謝!

+0

我看到在你的榜樣許多錯誤:1' read_file.read()'讀取並返回文件的全部內容,但是你沒有做任何事情。 2.你分配了'word =「ape」',但我沒有看到它的用處。如果有任何'數據',你不使用這個值,它將被替換爲下一行中的'for'。 3.'data.split()'返回由空格分隔的單詞列表(不起作用),但是你沒有做任何事情。 – KurzedMetal

回答

1
fileName = "test.txt" 
read_file = open(fileName, "r") 
with read_file as open_file: 
    data = open_file.read().rstrip() 
    keyword = "ape" 
    data = ' '.join(["\n"*(word == keyword) + word for word in data.split()]).strip() 
# data = data.replace(keyword, "\n"+keyword).strip() 
    print(data) 

OUTPUT:

# ape bear cat dog 
# ape elephant frog giraffe 
# ape horse iguana jaguar 
+1

如果'grape'出現,例如...需要小心...... –

+0

@JonClements好點 - 改變實現來說明這一點(保留舊的實現作爲註釋)。 – Brionius

0
import re 

file = "test.txt" 
for line in open(file, 'r'): 
    if(re.search('ape', line)): 
     print(line) 
3
>>> f = open("test.txt") 
>>> a = f.read() 
>>> f.close() 
>>> a = a.replace("ape", "\nape") 
>>> print(a) 

ape bear cat dog 
ape elephant frog giraffe 
ape horse iguana jaguar 
+0

這個效果很好,除了每行的末尾我都會得到一個「\」。有沒有辦法避免這種情況?謝謝! – hjames

1

試試這個,它打算什麼:

file = "test.txt" 
word = 'ape' 
read_file = open(file, "r") 
with read_file as data: 
    for line in data: 
     sp = line.split(word) 
     for s in sp: 
      if s: 
       print(word + s) 
1

假設你想了解控制流量和是不是想任何幻想用正則表達式或更換內容...

它看起來像你正在嘗試做這樣的事情(評論在線):

filename = 'test.txt'    # `file` is a Python built-in 
with open(filename, 'r') as data: # Open the file and close it when we're done 
    for line in data:    # This will read one line at a time and exit the loop at EOF 
     for word in line.strip().split(): # Strip off the newline and split the line into words 
      if word == 'ape':  # If we've found our keyword 
       print    #  Then Print a newline 
      print word,    # Print every word, without a trailing newline 

對於Python 3,你「會需要改變的語法不斷所以,稍微:

filename = 'test.txt' 
with open(filename, 'r') as data: 
    for line in data: 
     for word in line.strip().split(): 
      if word == 'ape': 
       print() 
      print(word, end=' ') 
+0

非常好,但你可以包含一個python 3版本嗎?這似乎是OP使用Python 3. – flornquake

+0

@flornquake:我活着給! – Johnsyweb

1

test.txt文件看起來像:

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar 

我想在屏幕上的最終結果是這樣的:

ape bear cat dog 
ape elephant frog giraffe 
ape horse iguana jaguar 

所以,你要「猿」的每一次出現是在一行的開始。

到目前爲止我的代碼:

file = "test.txt" 
read_file = open(file, "r") 
with read_file as data: 

有在拆分這兩種起來沒有任何意義。如果with與該文件一起完成,它將被關閉並且必須再次被編輯爲open()

所以只是做

with open(file, "r") as data: 

順便說一句,在你的代碼,read_filedata是相同的。

read_file.read() 

所以你看整個文件到內存中,並丟棄其結果。

print(data) 

打印文件對象。

word = "ape" 

分配...

for word in data: 

...並立即再次將其丟棄。

 data.split() 

拆分的數據,並丟棄結果。

 print(data) 

再次打印文件對象。

但是,正如您已經閱讀完整個文件,for循環可能根本沒有運行。

改進:

filename = "test.txt" # file is a builtin function 
hotword = "ape" 
with open(filename, "r") as read_file: 
    for line in read_file: 
     parts = line.split(hotword) 
     if not parts[0]: # starts with the hotword, so 1st part is empty 
      del parts[0] 
     print ("\n" + ape).join(parts) 

我發的文件中的變量,因爲我打算用很多不同的 次腳本。

名稱沒關係,但打開的文件不能被回收,因爲with關閉它。

當我測試代碼時,for循環在一個循環後沒有停止。

好嗎?它打印了什麼?

+0

它打印出text.txt文件,然後輸出正確的最終結果 - 但它重複該循環多次 – hjames

0

您可以使用re.sub來轉義不在行首的任何單詞,並在其之前放置一個換行符,以便您可以使用以下代碼。

請注意,此查找整個字 - 例如,grape將不會與匹配ape(不像所提供的解決方案str.replace):

import re 

word = 'ape' 
with open('yourfile') as fin: 
    line = next(fin, '') 
    print(re.sub(r'[^\b]({0}\s+)'.format(re.escape(word)), r'\n\1', line))