【问题标题】:extracting specific words (not keywords) from a log file从日志文件中提取特定单词(不是关键字)
【发布时间】:2019-06-25 12:54:07
【问题描述】:

我正在尝试从以下 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

【问题讨论】:

  • 为什么在您的预期输出中是 resync 而不是 INIT_VALUE
  • 我实际上是在寻找名字(在verilog中通常称为模块)。 resync 是一个模块名称。 INIT_VALUE 是一个参数,我不感兴趣。
  • 匹配你需要的东西不会很漂亮,因为你的实例名称没有使用一致的格式。例如。你有 xxxx_inst 和 inst_xxxx。参数使这更加复杂。我建议你使用这个工具regex101.com 直到你得到你需要的东西。
  • @user2532296,您能否提供更多有关您如何获得预期输出的详细信息?就像您在特定关键字之后需要一个关键字?或者您需要在关键字等之前使用它?

标签: python regex awk sed


【解决方案1】:

您可能需要一次读取多行来确定字符串是否是模块名称 或不。
请尝试以下方法:

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

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

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    使用 Perl

    $ perl -0777 -ne ' while ( /^\s+((\w+)\s+(\S+)\s+\(\s+\.)|^\s+(\S+)\s+\#\(\s+/gmsx ) { print "$2$4\n" } ' sample.log
    model_ip
    native_my_ip
    resync
    
    $
    

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多