0

每当找到 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

我已经写了这样的代码..你能修改并给我确切的代码吗

#!/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()
4

1 回答 1

0

使用 input-filefile_in和 output-file以及从作为参数给出的源文件中提取的字符串file_out列表,将找到,对于 in 中的任何行,无论中间包含的括号,交叉检查它与列表接受的字符串并将其(到新行)附加到:strings_to_filterextract_lines(file_in, file_out, strings_to_filter)file_inPUT_LOG(...);strings_to_filterout.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"
               ]
              )
于 2013-03-12T06:28:36.397 回答