Python 从日志文件中提取特定单词(非关键字)
我试图从下面的sample.txt中提取一些单词(如预期输出所示),并将它们放入列表中。我在提取正确的字段时遇到困难。我尝试过我的方法,但在大多数情况下都不起作用。我更喜欢使用python来实现这一点,但对其他语言开放。任何指向其他方法的指针都是非常感谢的 sample.logPython 从日志文件中提取特定单词(非关键字),python,regex,awk,sed,Python,Regex,Awk,Sed,我试图从下面的sample.txt中提取一些单词(如预期输出所示),并将它们放入列表中。我在提取正确的字段时遇到困难。我尝试过我的方法,但在大多数情况下都不起作用。我更喜欢使用python来实现这一点,但对其他语言开放。任何指向其他方法的指针都是非常感谢的 sample.log //********************************************************************************* // update section //******
//*********************************************************************************
// 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 )
);
我的尝试
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
上面的正则表达式查找可能的实例名或#(
)
希望这有帮助。使用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
$
为什么
resync
在您的预期输出中而不是INIT_值
?我实际上是在寻找名字(在verilog中通常称为模块).resync是一个模块名。INIT_值是一个参数,我对此不感兴趣。匹配您需要的内容不会很好,因为您的实例名使用的格式不一致。例如,您有xxxx_inst和inst_xxxx。这些参数使这一点更加复杂。我建议您使用此工具,直到获得所需的内容@user2532296,您能否提供更多有关如何获得预期输出的详细信息?例如,您需要在特定关键字之后添加关键字?或者在关键字之前添加关键字等?
$ 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
$