如何在Python中循环时将一行向下读几行?

2024-09-30 00:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道Python2.7中是否有一种方法可以通读文本文档以查找某些单词,然后如果找到这些单词,它将向下阅读几行以查找新词。如果找不到新单词,它将返回查找第一个单词。在

例如,我的文本文档如下所示:

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

这是我目前掌握的代码:

^{pr2}$

从现在开始我不知道该怎么办!我怎样才能让它搜索奶酪蛋糕,然后检查它们是否好吃?在


Tags: 方法代码section文本文档单词badgood蛋糕
3条回答

您还可以将记录从一个关键字分组到下一个关键字。

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

您可以在行迭代器中使用类似thisline=line.next()

你也可以继续读你的主循环中的行,比如

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

试着沿着这些思路。。。。在

 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()

相关问题 更多 >

    热门问题