[英]How to extract a specific line out of a text file
I have the code from the attached picture in a.can-file, which is in this case a text file.我在 a.can 文件中有来自附件图片的代码,在本例中是一个文本文件。 The task is to open the file and extract the content of the void function.任务是打开文件并提取 void function 的内容。 In this case it would be "$LIN::Kl_15 = 1;"在这种情况下,它将是“$LIN::Kl_15 = 1;”
This is what I already got:这是我已经得到的:
Masterfunktionsliste = open("C:/.../Masterfunktionsliste_Beispiel.can", "r")
Funktionen = []
Funktionen = Masterfunktionsliste.read()
Funktionen = Funktionen.split('\n')
print(Funktionen)
I receive the following list:我收到以下列表:
['', '', 'void KL15 ein', '{', '\t$LIN::Kl_15 = 1;', '}', '', 'void Motor ein', '{', '\t$LIN::Motor = 1;', '}', '', '']
And now i want to extract the $LIN::Kl_15 = 1;
现在我想提取$LIN::Kl_15 = 1;
and the $LIN::Motor = 1;
和$LIN::Motor = 1;
line into variables.行成变量。
Use the {
and }
lines to decide what lines to extract:使用{
和}
行来决定要提取哪些行:
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
should now have values ['$LIN::Kl_15 = 1;', '$LIN::Motor = 1;']
body_lines
现在应该有值['$LIN::Kl_15 = 1;', '$LIN::Motor = 1;']
You can loop through the list, search for your variables and save it as dict:您可以遍历列表,搜索变量并将其保存为 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 is {'$LIN::Kl_15': '1', '$LIN::Motor': '1'}
output 是{'$LIN::Kl_15': '1', '$LIN::Motor': '1'}
now you can access your new variables with extracted['$LIN::Motor']
which is 1
现在您可以使用extracted['$LIN::Motor']
访问新变量,即1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.