python和shell哪个快_有没有可能让这个shell脚本更快?
我的任務(wù)是創(chuàng)建一個(gè)以一個(gè)巨大的文本文件作為輸入的腳本。然后它需要找到所有單詞和出現(xiàn)的次數(shù),并創(chuàng)建一個(gè)新文件,每行顯示一個(gè)唯一的單詞及其出現(xiàn)的次數(shù)。在
以包含以下內(nèi)容的文件為例: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.
我需要?jiǎng)?chuàng)建一個(gè)如下所示的文件:
^{pr2}$
為此,我使用tr、sort和{}編寫了一個(gè)腳本:#!/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
它的作用是按空格分隔單詞。如果單詞包含-_?!.;:,我會(huì)再次將它們分解成單詞。我刪除了標(biāo)點(diǎn)符號(hào)、特殊字符和數(shù)字,并將整個(gè)字符串轉(zhuǎn)換為大寫。完成后,我對(duì)它進(jìn)行排序并通過uniq將其轉(zhuǎn)換為我想要的格式。在
現(xiàn)在我下載了txt格式的圣經(jīng),并用它作為輸入。我得到的時(shí)機(jī):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
我對(duì)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')
當(dāng)我執(zhí)行腳本時(shí),我得到了: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
如您所見,它運(yùn)行在7.23s中,而shell腳本運(yùn)行在16.17s中。我嘗試過使用更大的文件,而Python似乎總是成功的。我有幾個(gè)問題要問上面的塞納里奧:既然shell命令是用C編寫的,為什么Python腳本更快?我知道shell腳本可能不是最佳腳本。在
如何改進(jìn)shell腳本?在
我可以改進(jìn)Python腳本嗎?在
明確地說,我并不是在比較Python和shell腳本。我不想挑起一場戰(zhàn)爭,也不需要任何其他語言的答案來比較自己更快。使用UNIX的原理,通過管道發(fā)送小命令來完成任務(wù),如何使shell腳本更快?在
總結(jié)
以上是生活随笔為你收集整理的python和shell哪个快_有没有可能让这个shell脚本更快?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql搭建测试环境的步骤_如何搭建测
- 下一篇: python中gettext文件格式_P