2013-03-12 22 views
0

我試圖從PUT_LOG標記中提取(LOG_LEVEL_DEBUG,CAPTIVE_RECVD_SIGCHLD),只要找到PUT_LOG標記,我只想提取其中的信息並將其放入另一個文件中。Python發現特定字符串時從文件中提取數據

請找到的代碼片段從那裏要提取信息...

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 

我已經寫了這樣的代碼,你..can修改,並給我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

這將是很好看你有沒有嘗試過的東西。這是所有*「你告訴我你的,我告訴你我的」*在SO :) – root 2013-03-12 06:09:48

+0

你明白了嗎..我的預期結果是什麼 – Manu 2013-03-12 06:24:46

回答

0

使用輸入文件file_in和輸出文件file_out以及從源文件中提取的字符串列表strings_to_filter作爲參數給出,extract_lines(file_in, file_out, strings_to_filter)將發現,對於file_in中的任何行,無論括號的PUT_LOG(...); TS包含在中間,交叉檢查它違反公認的字符串列表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" 
       ] 
      ) 
+0

非常感謝..我試試這個......其實我是新的python。 .. – Manu 2013-03-12 06:33:41

+0

什麼是os然後我怎麼可以intialsie plz給我complte代碼 – Manu 2013-03-12 06:38:41

+0

當然。只要您根據您的上下文指定'file_in','file_out'和'search_string',就可以開箱即用。如果您需要搜索複雜模式而不是簡單的字符串,請告訴我,我可以將其添加到上面的示例中。 – bossi 2013-03-12 06:38:50