【发布时间】:2015-10-20 20:21:47
【问题描述】:
我正在尝试编写一个函数,它读取文本文件直到找到一个单词(比如“hello”),然后打印从字符串 1 开始的下 x 行字符串(比如“start_description”)直到字符串 2 (比如“end_description”)。
hello
start_description 123456 end_description
函数应该看起来像 description("hello") 并且下面的输出应该看起来像
123456
这有点难以解释。我知道如何在文本文件中找到特定的单词,但我不知道如何打印,如前所述,两个字符串(start_description 和 end_description)之间的下几行。
编辑1: 我找到了一些代码,可以打印接下来的 8、9、... 行。但是因为两个字符串之间的文本是可变长度的,所以这不起作用...
编辑2: 基本上它与这篇文章中的问题相同:Python: Print next x lines from text file when hitting string,但 range(8) 对我不起作用(参见 EDIT1)。
输入文件可能如下所示:
HELLO
salut
A: 123456.
BYE
au revoir
A: 789123.
代码应如下所示:
import re
def description(word):
doc = open("filename.txt",'r')
word = word.upper()
for line in doc:
if re.match(word,line):
#here it should start printing all the text between start_description and end_description, for example 123456
return output
print description("hello")
123456
print description("bye")
789123
【问题讨论】:
-
请编辑您的帖子以包含示例输入文件和预期输出
-
我包含了到目前为止的代码和预期的输出。
-
请编辑您的帖子以包含您的输入文件示例和预期输出
-
现在够精确了吗? :-)