簡體   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