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搭建测试环境的步骤_如何搭建测
- 下一篇: mysql视图有哪几种_数据库报表的视图