![](/img/trans.png)
[英]How to extract the next line after a specific keyword when there are words in between using regex in Python?
[英]How to extract line after line till a specific keyword and then declare to a variable
我目前正在嘗試提取一些行,直到從.txt文件中找到一個關鍵字以聲明帶有文本的變量為止。 現在,我有以下代碼來獲取我想要的行:
def extract_line(row):
a = open("Z:/xyz/xyz/test.txt","r", encoding="utf-8")
b = a.readlines()
a.close()
count = 0
for line in b:
count += 1
if count == row:
if "REQUIREMENT TYPE " in line:
break
else:
print(line)
extract_line(row + 1)
這對於打印行很有效,但是我無法提取行以使用文本聲明變量。 我怎么做?
我不確定為什么要遞歸調用該函數。
如果我的問題正確,那么您要存儲獲得的行,直到您按下某個關鍵字。 按下關鍵字后,您想打斷它,並且需要一個變量來讀取直到此為止的行。
您可以使用以下代碼執行此操作:
with open("file.txt", "r") as f:
extracted_line = [] # create an empty list to store the extracted lines
for line in f:
if 'REQUIREMENT TYPE' in line: # if keyword is present in the current line, break
break
else:
extracted_line.append(line) # else, append the line to store them later
stored_lines = ''.join(extracted_line) # variable which stores the lines till keyword
print stored_lines
f.close()
我已經在代碼旁邊添加了注釋。 希望這能回答您的問題。 讓我知道您是否需要任何澄清。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.