我有一個創建腳本的任務,它將一個巨大的文本文件作爲輸入。然後需要查找所有單詞和出現次數,並創建一個新文件,每行顯示一個唯一的單詞及其出現次數。是否有可能使這個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
這是幹什麼的es將空格分隔爲分隔符。如果這個詞包含-_?!.;:
我將它們再次分解成單詞。我刪除了標點,特殊字符和數字,並將整個字符串轉換爲大寫。一旦完成,我將它分類並通過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似乎取得了勝利。我對上面的senario有幾個問題:
- 爲什麼Python腳本更快,因爲shell命令是用C編寫的?我意識到shell腳本可能不是最佳的腳本。
- 我該如何改進shell腳本?
- 我可以改進Python腳本嗎?
要清楚我沒有比較Python shell腳本。我並非試圖開始一場火焰戰爭,或者不需要任何其他語言的答案來比較自己的速度。使用管道小命令執行任務的UNIX哲學,我如何更快地創建shell腳本?
我建議標題更改爲類似「是否有可能使這個shell腳本更快?「,使用如此不同的python腳本onl y作爲比較點。這將消除python和shell之間無用的和無關主題討論的風險。 – 2012-08-16 13:11:19
我不認爲使用很多小命令很好地完成單個任務的\ nix理念已經到位,因爲它是最高效的*。它的原因是因爲使用我們的工具,您可以完成如此多的任務,爲您的簡單任務節省大量時間開發新程序。 – mgilson 2012-08-16 13:26:31
Python也是用C編寫的。 「用C寫成」不足以讓事情變得更快 - 插入層(以及所有讀寫流水線和管線)都有開銷。 – 2012-08-16 14:15:55