代码之家  ›  专栏  ›  技术社区  ›  O. Schultz

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

  •  0
  • O. Schultz  · 技术社区  · 7 年前

    我目前正在尝试提取一些行,直到我从中找到一个关键字。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)
    

    它可以很好地打印出这些行,但我无法提取这些行来声明带有文本的变量。我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  0
  •   nj2237 Rowland Ogwara    7 年前

    我不知道为什么要递归调用该函数。

    如果我答对了你的问题,你想存储你得到的行,直到你找到某个关键字。一旦你点击了关键字,你就想中断,你需要一个变量来记录你读到的行。

    可以使用以下代码执行此操作:

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

    我在代码旁边加了注释。希望这能回答你的问题。如果您需要任何澄清,请告诉我。