java perl python 文本处理_文本处理-Python与Perl performan

下面是我的Perl和Python脚本,它可以对大约21个日志文件执行一些简单的文本处理,每个文件大约300 KB到1 MB(最大值)x 5次重复(总共125个文件,因为log重复了5次)。

Python代码(修改为使用编译的re和使用re.I的代码)#!/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)

Perl代码#!/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";

}

}

而且,在我的电脑上,两个代码生成的10790行结果文件完全相同。这里是Cygwin的Perl和Python实现的计时。User@UserHP /cygdrive/d/tmp/Clipboard

# time /tmp/scripts/python/afs/process_file.py *log* *log* *log* *log* *log* >

summarypy.log

real 0m8.185s

user 0m8.018s

sys 0m0.092s

User@UserHP /cygdrive/d/tmp/Clipboard

# time /tmp/scripts/python/afs/process_file.pl *log* *log* *log* *log* *log* >

summarypl.log

real 0m1.481s

user 0m1.294s

sys 0m0.124s

最初,使用Python需要10.2秒,使用Perl进行简单的文本处理只需要1.9秒。

(UPDATE)但是,在Python的编译版本之后,Python现在需要8.2秒,Perl需要1.5秒。Perl仍然要快得多。

有没有办法提高Python的速度,或者很明显Perl将是简单文本处理的快速方法。

顺便说一句,这不是我对简单文本处理所做的唯一测试。。。而且,我制作源代码的每一种不同方法,总是Perl以很大的优势胜出。而且,Python在简单的m/regex/匹配和打印方面的表现也从未如此出色。Please do not suggest to use C, C++, Assembly, other flavours of

Python, etc.

I am looking for a solution using Standard Python with its built-in

modules compared against Standard Perl (not even using the modules).

Boy, I wish to use Python for all my tasks due to its readability, but

to give up speed, I don't think so.

So, please suggest how can the code be improved to have comparable

results with Perl.

更新:2012-10-18

正如其他用户所建议的,Perl有它的位置,Python有它的位置。

因此,对于这个问题,我们可以安全地得出这样的结论:对于成百上千个文本文件的每一行上的简单正则表达式匹配,并将结果写入文件(或打印到屏幕上),Perl将始终在这项工作的性能上获胜。就这么简单。

请注意,当我说Perl在性能上获胜时。。。只比较了标准Perl和Python。。。不诉诸于一些模糊的模块(对于像我这样的普通用户来说是晦涩的),也不从Python或Perl调用C、C++、汇编库。我们没有时间学习所有这些额外的步骤和简单的文本匹配工作的安装。

因此,Perl支持文本处理和regex。

Python在其他地方也有自己的地位。

更新2013-05-29:做类似比较的优秀文章is here。Perl再次赢得了简单文本匹配。。。更多细节,请阅读文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值