python和shell哪个快_有没有可能让这个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.
我需要创建一个如下所示的文件:
^{pr2}$
为此,我使用tr、sort和{}编写了一个脚本:#!/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中,而shell脚本运行在16.17s中。我尝试过使用更大的文件,而Python似乎总是成功的。我有几个问题要问上面的塞纳里奥:既然shell命令是用C编写的,为什么Python脚本更快?我知道shell脚本可能不是最佳脚本。在
如何改进shell脚本?在
我可以改进Python脚本吗?在
明确地说,我并不是在比较Python和shell脚本。我不想挑起一场战争,也不需要任何其他语言的答案来比较自己更快。使用UNIX的原理,通过管道发送小命令来完成任务,如何使shell脚本更快?在
总结
以上是生活随笔为你收集整理的python和shell哪个快_有没有可能让这个shell脚本更快?的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: mysql搭建测试环境的步骤_如何搭建测
- 下一篇: python中gettext文件格式_P