首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python 怎么得到匹配到string的行

2012-09-14 
python 如何得到匹配到string的行文件名:change.log我想匹配到error并返回行.类似于grep error change.log

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

热点排行