如何逐行提取到特定关键字,然后声明为变量
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()
我在代码旁边添加了注释。希望这能回答您的问题。如果您需要任何说明,请告诉我。
我目前正在尝试提取一些行,直到我从 .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()
我在代码旁边添加了注释。希望这能回答您的问题。如果您需要任何说明,请告诉我。