2015-10-20 120 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