python脚本与shell脚本速度对比_python – 可以使这个shell脚本更快吗?

我有一个任务,创建一个脚本,它将一个巨大的文本文件作为输入.然后需要查找所有单词和出现次数,并创建一个新文件,每行显示一个唯一的单词及其出现.

举个例子来看这个内容的文件:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor

incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud

exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure

dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt

mollit anim id est laborum.

我需要创建一个如下所示的文件:

1 AD

1 ADIPISICING

1 ALIQUA

...

1 ALIQUIP

1 DO

2 DOLOR

2 DOLORE

...

为此,我用tr,sort和uniq写了一个脚本:

#!/bin/sh

INPUT=$1

OUTPUT=$2

if [ -a $INPUT ]

then

tr '[:space:][\-_?!.;\:]' '\n' < $INPUT |

tr -d '[:punct:][:special:][:digit:]' |

tr '[:lower:]' '[:upper:]' |

sort |

uniq -c > $OUTPUT

fi

这样做是将空格分隔为分隔符.如果这个词包含-_?!.;;:我再次将它们打破了.我删除标点符号,特殊字符和数字,并将整个字符串转换为大写.一旦完成,我将其排序并通过uniq传递给我想要的格式.

现在我以txt格式下载了圣经,并将其用作输入.时间这个我得到了

scripts|$time ./text-to-word.sh text.txt b

./text-to-word.sh text.txt b 16.17s user 0.09s system 102% cpu 15.934 total

我用Python脚本也是一样的:

import re

from collections import Counter

from itertools import chain

import sys

file = open(sys.argv[1])

c = Counter()

for line in file.readlines():

c.update([re.sub('[^a-zA-Z]', '', l).upper()

for l in chain(*[re.split('[-_?!.;:]', word)

for word in line.split()])])

file2 = open('output.txt', 'w')

for key in sorted(c):

file2.write(key + ' ' + str(c[key]) + '\n')

当我执行脚本我得到:

scripts|$time python text-to-word.py text.txt

python text-to-word.py text.txt 7.23s user 0.04s system 97% cpu 7.456 total

正如你可以看到它运行在7.23s与运行在16.17s的shell脚本.我尝试使用更大的文件,总是Python似乎胜利.我对上述情况有几个问题:

>为什么Python脚本更快,因为shell命令是用C写的?我确实认识到shell脚本可能不是最佳的.

>如何改进shell脚本?

>我可以改进Python脚本吗?

要清楚我不是将Python与shell脚本进行比较.我不是试图开始一场火焰战,或者不用任何其他语言的答案比较本身更快.使用UNIX的管道小命令做一个任务,我如何使shell脚本更快?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值