Python搜索.text文件,当找到匹配项时,在匹配的单词后打印多行

时间:2013-11-27 14:44:04

标签: python

我正在寻找一个文件,当找到我要找的单词时,我希望它打印出该单词下面的8行。请记住,我是一个完整的菜鸟,我只做了几个星期。这就是我所拥有的,但它不起作用(显然!):

name = input("What did you put as the calculation name?: ")
saved_calcs = open("saved_calcs.txt", "r")
lines = saved_calcs.read()
i = lines.index(name)
for line in lines[i-0:i+9]:
    print (line)
saved_calcs.close()

2 个答案:

答案 0 :(得分:1)

lines.index将查找名称正确的行。 你需要遍历这些行并搜索你的字符串。

i = -1
for x, line in enumerate(lines):
    if line.find(name) != -1:
        i = x
        break
....

答案 1 :(得分:0)

不确定这是否是您要查找的内容,但如果您的输入与文件中一行中的内容完全匹配,则代码可能如下所示:

name = input("What did you put as the calculation name?: ")
saved_calcs = open("saved_calcs.txt", "r")
lines = saved_calcs.read()
split_lines = lines.split("\n")
index = split_lines.index(str(name))+1
for line in split_lines[index:index+8]:
    print line
saved_calcs.close()