我想知道是否有方法在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()
我不知道是什麼,從在這一點上做的!我怎樣才能找到芝士蛋糕,然後檢查他們的味道是否好?
看起來像你應該使用正則表達式(regex,'re' python模塊),使用're.MULTILINE'或're.DOTALL'標誌。 – heltonbiker 2012-02-06 19:51:52
風格點:你的「文件名」不是文件名,它是文件對象本身。 – DSM 2012-02-06 21:26:58