Python语法简单,而且通过缩进的方式来表现层次结构,代码非常简明易懂,对初学者来说,比较容易上手。
Perl的模式匹配非常强大,同时匹配的符号有很多种,难以阅读和维护。
在文本处理方面,python通过加载re模块来实现模式匹配的查找和替换。而Perl内置就有模式匹配功能。
note:内置命令和外部命令的区别。
通过代码来直接做比较。
python版:
#!/usr/bin/python
import re
import fileinput
exists_re = re.compile(r'^(.*?) INFO.*Such a record already exists', re.I)
location_re = re.compile(r'^AwbLocation (.*?) insert into', re.I)
for line in fileinput.input():
fn = fileinput.filename()
currline = line.rstrip()
mprev = exists_re.search(currline)
if(mprev):
xlogtime = mprev.group(1)
mcurr = location_re.search(currline)
if(mcurr):
print fn, xlogtime, mcurr.group(1)
#!/usr/bin/perl
while (<>) {
chomp;
if (m/^(.*?) INFO.*Such a record already exists/i) {
$xlogtime = $1;
}
if (m/^AwbLocation (.*?) insert into/i) {
print "$ARGV $xlogtime $1\n";
}
}
time process_file.py *log > summarypy.log
real 0m8.185s
user 0m8.018s
sys 0m0.092s
time process_file.pl *log > summaypl.log
real 0m1.481s
user 0m1.294s
sys 0m0.124s
所以在处理大文件如大日志方面,用perl更好,因为更快。
如果对速度要求不是很严格的话,用python更好,因为python简洁易懂,容易维护和阅读。
为什么在文本处理时,Perl比Python快很多呢?
这是因为Perl的模式匹配是其内置功能,而Python需要加载re模块,使用内置命令比外部命令要快很多。
用type命令可以分辨内部命令与外部命令。
原文地址:http://blog.csdn.net/jenny_yu1025/article/details/45367013