python 如何得到匹配到string的行

文件名:change.log
我想匹配到error并返回行.

类似于grep error change.log

用python如何实现?




change.log 文件内容

Please wait while, the wizard is runing now!

if you arrived at this page by clicking a link, check the website address in the address bar to be sure that it is the address you were expecting.

when going to a website with an address such as https://example.com try adding the 'www' to address.

if you choose to ignore this error and continue, do not enter private information into the website.

For more information, see 'Certificate Error' in Internet Explorer Help!


用perl实现如下:
#!/usr/bin/perl -w

open(F1,"change.log"||die "Cannot open change.log!";

my @grp=<F1>;

foreach my $va(@grp) {
        #print $va;

if ($va=~/error/i) {

        print "$va\n";
}
}


python怎么匹配?

 

 

 

1.

print ''.join([x for x in open('change.log').readlines() if x.find('error')!=-1])

 

2.

print (''.join([x for x in open('change.log').readlines() if re.search('error',x)]))

 

3.忽略大小写

转换成小写或大写来判断就等于忽略大小写了

print( "".join([x for x in open('change.log').readlines() if x.lower().find('error')!=-1]))

print( "".join([x for x in open('change.log').readlines() if x.upper().find('ERROR')!=-1]))

 

正则

print (''.join([x for x in open('change.log').readlines() if re.search('error',x,re.I)]))

 

 

1.

#!/usr/bin/python

a=open("change.log").readlines()

for x in a:
 if x.find("error") != -1:
  print(x)

 

2.

#!/usr/bin/python
import re

a=open("change.log").readlines()
#print(a)

for x in a:
 #print(x)
 if re.search("error",x,re.I):
  print(x,end="")

 

 

http://bbs.chinaunix.net/thread-3729007-1-1.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值