简体   繁体   English

如何逐行提取直到特定的关键字,然后声明为变量

[英]How to extract line after line till a specific keyword and then declare to a variable

I'm currently trying to extract some lines till i reach a keyword out of a .txt file to declare a variable with the text. 我目前正在尝试提取一些行,直到从.txt文件中找到一个关键字以声明带有文本的变量为止。 Right now I have this code to get the lines I want to have: 现在,我有以下代码来获取我想要的行:

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)

which works fine for printing out the lines, but I can't extract the lines to declare a variable with the text. 这对于打印行很有效,但是我无法提取行以使用文本声明变量。 How do I do that? 我怎么做?

I'm not sure why you are calling the function recursively. 我不确定为什么要递归调用该函数。

If I got your question right, you want to store the lines you get until you hit a certain keyword. 如果我的问题正确,那么您要存储获得的行,直到您按下某个关键字。 Once you hit the keyword, you want to break and you need a variable to have the lines you have read until that point. 按下关键字后,您想打断它,并且需要一个变量来读取直到此为止的行。

You can do this with the following code: 您可以使用以下代码执行此操作:

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()

I have put comments beside the code. 我已经在代码旁边添加了注释。 Hope this answers your question. 希望这能回答您的问题。 Let me know if you need any clarification. 让我知道您是否需要任何澄清。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM