2012-02-06 31 views
1

我想知道是否有方法在Python 2.7中通過文本文件來查找某些單詞,然後如果它找到這些單詞,它會讀取幾行以查找新單詞。如果它找不到新單詞,它將返回查找第一個單詞。如何在Python中循環時讀一行幾行?

例如我的文本文檔看起來像這樣:

1.Section 

2. Cheesecake 
3. 0 
4. 0 
5. 0 
6. Tastes good 
7. 0 
8. 0 
9. Donut 
10. 0 
11. Tastes good 
12. 0 
13. Cheesecake 
14. 0 
15. 0 
16. Tastes bad 

這是我到目前爲止的代碼:

import sys 

fileName = open("filename.txt", "r") 

while True: 
    line = fileName.readline() 
    if line is None: break 
    else: 
     if line.startswith('CHEESECAKE'): 
      print (line) 
      x = raw_input(" Continue? ") 
      if x == "n": 
       sys.exit() 

我不知道是什麼,從在這一點上做的!我怎樣才能找到芝士蛋糕,然後檢查他們的味道是否好?

+0

看起來像你應該使用正則表達式(regex,'re' python模塊),使用're.MULTILINE'或're.DOTALL'標誌。 – heltonbiker 2012-02-06 19:51:52

+0

風格點:你的「文件名」不是文件名,它是文件對象本身。 – DSM 2012-02-06 21:26:58

回答

0

您還可以將記錄從一個關鍵字分組到下一個關鍵字。

import sys

def process_group(list_in): if len(list_in): for rec in list_in: if rec.startswith("Tastes"): print "Tastes found for", list_in[0] return print "Tastes NOT found for", list_in[0]

open_file = open("filename.txt", "r")

group_list=[] start_list=["CHEESECAKE", "DONUT"] for line in open_file: for st in start_list: if line.upper().startswith(st): ## process this group print (line) process_group(group_list) group_list=[] ## an empty list for the next group x = raw_input(" Continue? ") if x == "n": sys.exit() group_list.append(line)

process_group(group_list) # process the last group

0

可以向前行迭代器類似thisline=line.next()

你還可以繼續讀你的東西主循環中線條狀

for tmp in line: 
    if tmp eq "bla" : 
     ... do something. 
     break 
1

嘗試沿着這些線路的東西....步

if line.startswith('CHEESECAKE'): 
     do something 
    elseif line.startswith('tastegood'): 
    do something 
else: 
    do something 
    print (line) 
    x = raw_input(" Continue? ") 
    if x == "n": 
      sys.exit() 
0

使用正則表達式:

filecontent = open("filename.txt", "r").read() 
results = re.findall('Cheesecake.*?Tastes\s+?(\w*)\s+?', filecontent, re.DOTALL) 
print results 

在文件中查找模式的最佳方法是一次只讀一次,除非它是非常長的文件。 然後,您使用re.DOTALL標誌使用正則表達式。這意味着換行符被視爲常規字符,允許搜索模式跨越多行。

如果您願意,您可以將其中的一部分與您以前的代碼混合在一起,以允許用戶一次進行一次匹配。然後,您應該使用re.search(pattern, text, re.DOTALL).group(1)獲取每個單獨的匹配內容。