我试图写一个函数读取文本文件直到找到一个单词(比如“hello”),然后打印下一个以字符串1开头的x行(说“start_description”)直到字符串2(比如说“end_description”)。从字符串1打印下一个x行,直到字符串2
hello
start_description 123456 end_description
的功能应该像描述(“你好”)和下面的输出应该看起来像
123456
这是一个有点难以解释。我知道如何在文本文件中找到某个单词,但我不知道如何打印这两个字符串(start_description和end_description)之间的接下来几行。
编辑1: 我发现了一些代码,它允许打印接下来的8,9,...行。但由于两个字符串之间的文本长度可变,所以不起作用...
编辑2: 基本上它与本帖中的问题相同:Python: Print next x lines from text file when hitting string,但范围(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
请编辑您的文章以包含样本输入文件和期望的输出 – inspectorG4dget
我包含了迄今为止的代码和预期的输出。 – neacal
请编辑您的文章,以包含您的输入文件的样本,以及期望的输出 – inspectorG4dget