2015-10-20 121 views
0

我试图写一个函数读取文本文件直到找到一个单词(比如“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 
+0

请编辑您的文章以包含样本输入文件和期望的输出 – inspectorG4dget

+0

我包含了迄今为止的代码和预期的输出。 – neacal

+0

请编辑您的文章,以包含您的输入文件的样本,以及期望的输出 – inspectorG4dget

回答

0

下面是一个使用分割的方式:

start_desc = 'hello' 
end_desc = 'bye' 
str = 'hello 12345\nabcd asdf\nqwer qwer erty\n bye' 

print str.split('hello')[1].split('bye')[0] 

第一分割将导致在:

('', ' 12345\nabcd asdf\nqwer qwer erty\n bye') 

所以第二个元素喂到第二裂,它会导致:

('12345\nabcd asdf\nqwer qwer erty\n ', '') 

使用的第一要素。

如果您愿意,可以使用strip()删除周围空间。

0
def description(infilepath, startblock, endblock, word, startdesc, enddesc): 
    with open(infilepath) as infile: 
     inblock = False 
     name = None 
     found = False 
     answer = [] 
     for line in infile: 
      if found and not inblock: return answer 
      if line.strip() != startblock and not inblock: continue 
      if line.strip() == startblock: inblock = True 
      elif line.strip() == endblock: inblock = False 
      if not line.startswith(startdesc): 
       name = line.strip() 
       continue 
      if name is not None and name != word: continue 
      if not line.startswith(startdesc): continue 
      answer.append(line.strip().lstrip(startdesc).rstrip(enddesc)) 
+0

感谢您的代码,@ inspectorG4dget,我认为这可能有所帮助。我会在几个小时后再看看它(现在欧洲已经是晚上11点了)。 – neacal