繁体   English   中英

如何从文本文件中提取特定行

[英]How to extract a specific line out of a text file

我在 a.can 文件中有来自附件图片的代码,在本例中是一个文本文件。 任务是打开文件并提取 void function 的内容。 在这种情况下,它将是“$LIN::Kl_15 = 1;” 在此处输入图像描述

这是我已经得到的:

Masterfunktionsliste = open("C:/.../Masterfunktionsliste_Beispiel.can", "r")
Funktionen = []
Funktionen = Masterfunktionsliste.read() 
Funktionen = Funktionen.split('\n')
print(Funktionen)

我收到以下列表:

['', '', 'void KL15 ein', '{', '\t$LIN::Kl_15 = 1;', '}', '', 'void Motor ein', '{', '\t$LIN::Motor = 1;', '}', '', '']

现在我想提取$LIN::Kl_15 = 1; $LIN::Motor = 1; 行成变量。

使用{}行来决定要提取哪些行:

scope_depth = 0
line_stack = list(reversed(Funktionen))
body_lines = []

while len(line_stack) > 0:
    next = line_stack.pop()
    if next == '{':
        scope_depth = scope_depth + 1
    elif next == '}':
        scope_depth = scope_depth - 1
    else:
        # test that we're inside at lest one level of {...} nesting
        if scope_depth > 0:
            body_lines.append(next)

body_lines现在应该有值['$LIN::Kl_15 = 1;', '$LIN::Motor = 1;']

您可以遍历列表,搜索变量并将其保存为 dict:

can_file_content = ['', '', 'void KL15 ein', '{', '\t$LIN::Kl_15 = 1;', '}', '', 'void Motor ein', '{', '\t$LIN::Motor = 1;', '}', '', '']
extracted = {}

for line in can_file_content:
    if "$LIN" in line:  # extract the relevant line
        parsed_line = line.replace(";", "").replace("\t", "")  # remove ";" and "\t"
        variable, value = parsed_line.split("=")  # split on "="
        extracted[variable.strip()] = value.strip()  # remove whitespaces

output 是{'$LIN::Kl_15': '1', '$LIN::Motor': '1'}
现在您可以使用extracted['$LIN::Motor']访问新变量,即1

暂无
暂无

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

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