python-从日志文件中提取特定单词(不是关键字)

我正在尝试从下面的sample.txt中提取一些单词(如预期的输出所示)并将它们放在列表中.我在提取正确字段方面面临困难.我已经尝试了我的方法,但是在大多数情况下不起作用.我更喜欢使用python来执行此操作,但是可以使用其他语言.任何其他方法的指针都将受到赞赏.

sample.log

//*********************************************************************************
// update section
//*********************************************************************************
      for (i=0; i< models; i = i+1) begin:modelgen

     model_ip model_inst
         (
          .model_powerdown(model_powerdown),.mcg(model_powerdown),.lambda(_lambda[i])
          );
      assign fnl_verifier_lock = (tx_ready & rx_ready) ? &verifier_lock :1'b0;

   native_my_ip native_my_inst
     (
      .tx_analogreset(tx_analogreset),//.unused_tx_parallel_data({1536{1'b0}})

      );

   // END Section I : 
   //*********************************************************************************
   resync 
     #(
       .INIT_VALUE (1)
       ) inst_reset_sync 
       (
    .clk    (tx_coreclkin),.reset  (!tx_ready),// tx_digitalreset from reset 
    .d      (1'b0),.q      (srst_tx_common  )
    );

预期产量

model_ip
native_my_ip
resync

我的尝试

import re

input_file = open("sample.log","r")
result = []
for line in input_file:
    # need a more generic match condition to extract expected results 
    match_instantiation = re.match(r'\s(.*) ([a-zA-Z_0-9]+) ([a-zA-Z_0-9]+)_inst (.*)',line)


    if match_instantiation:
    print match_instantiation.group(1)
    result.append(match_instantiation.group(1))
    else:
        continue
最佳答案
您可能需要一次阅读多行以确定字符串是否是模块名称
或不.
请尝试以下操作:

import re

input_file = open("sample.log","r")
lines = input_file.read()   # reads all lines and store into a variable
input_file.close()
for m in re.finditer(r'^\s*([a-zA-Z_0-9]+)\s+([a-zA-Z_0-9]+\s+\(|#\()',lines,re.MULTILINE):
    print m.group(1)

产生:

model_ip
native_my_ip
resync

上面的正则表达式会查找可能的实例名称或#(.

希望这可以帮助.

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...