我试图在找到PUT_LOG标签时从PUT_LOG标签中提取(LOG_LEVEL_DEBUG,CAPTIVE_RECVD_SIGCHLD)我只是想在其中提取信息并将其放入另一个文件中。
请找到想要提取信息的代码段......
PUT_LOG(LOG_LEVEL_DEBUG, CAPTIVE_EXECUTE_CMD,1,STRING, cmd);
PUT_LOG(LOG_LEVEL_DEBUG, CAPTIVE_EXECUTE_CMD,1,STRING, cmd);
PUT_LOG(LOG_LEVEL_DEBUG_ERR, CAPTIVE_EXECUTE_CMD_FAILED,1, STRING, cmd);
enter code here
my out put should be like this
LOG_LEVEL_DEBUG
CAPTIVE_EXECUTE_CMD
LOG_LEVEL_DEBUG_ERR
CAPTIVE_EXECUTE_CMD_FAILED
我已经编写了这样的代码..你可以修改并给我一些exctly代码
#!/usr/bin/env python
inFile = open("data.c")
outFile = open("result.txt", "w")
buffer = []
keepCurrentSet = True
for line in inFile:
buffer.append(line)
if line.startswith("PUT_LOG"):
#---- starts a new data set
if keepCurrentSet:
outFile.write("".join(buffer))
#now reset our state
keepCurrentSet = False
buffer = []
elif line.startswith("LOG_LEVEL_DEBUG"):
keepCurrentSet = True
inFile.close()
outFile.close()
答案 0 :(得分:0)
使用输入文件file_in
和输出文件file_out
以及要从作为参数提供的源文件中提取的字符串列表strings_to_filter
,extract_lines(file_in, file_out, strings_to_filter)
将找到file_in
中的任何行,无论PUT_LOG(...);
的括号是否包含在中间,将其与已接受字符串的strings_to_filter
列表进行交叉检查并将其附加(换行)到out.txt
:
import os
import re
def extract_lines(file_in, file_out, strings_to_filter):
with open(file_in) as f_in, open(file_out, "a+") as f_out:
for line in f_in:
res = re.search("(PUT_LOG\()(.*)(\)\;)", line)
if res is not None:
i = 0
for segment in res.group(2).split(","):
segment = segment.strip()
if segment in strings_to_filter and i < 2:
print(segment, file=f_out)
i += 1
extract_lines(
os.path.realpath("path/to/log_file.txt"),
os.path.realpath("path/to/output_file.txt"),
[
"CAPTIVE_EXECUTE_CMD",
"CAPTIVE_EXECUTE_CMD_FAILED",
"CAPTIVE_RECVD_SIGCHLD",
"LOG_LEVEL_DEBUG",
"LOG_LEVEL_DEBUG_ERR"
]
)