11-18
更新支持中/英文单词翻译的函数脚本,同时也加入了误输入数字的检测:
ts() { word=`echo "$1"|egrep -v "[0-9]|[[:punct:]]"` [ -z "$word" ] && echo "检测到不支持的字符!" && return 1; [ $# -ne 1 ] && echo "需要且仅支持一个中/英文单词!" && return 1; word=`echo "$1"|egrep "^[a-zA-Z]+$"` echo echo "${1}:" if [ -n "$word" ];then wget -qO- "http://dict.cn/$1"|\ sed -n '/"phonetic"/,/"padding-top:/p'|\ sed -e 's/<[^>]*>//g' -e 's/[[:space:]]//g'|\ tr -d '\n'|\ sed -e 's/]/]\t/' -e 's/[a-z]\{1,\}\./\n&/g' echo echo return 0; else wget -qO- "http://dict.cn/$1"|\ sed -n '/"phonetic"/,/\/ul/p'|\ sed -e 's/<[^>]*>//g' -e 's/[[:space:]]//g'|\ egrep -v "new|基本释义|^$" echo return 0; fi }
近来在学习linux跟shell脚本。英文又多年不用还给教师了。遇到不懂的单词都要开个词霸网页词典来翻译,久了多有不爽。偶然找到http://www.iteye.com/topic/819440中提到一个翻译英文单词的shell脚本,可惜是多年以前的,并且用的还是如今被墙的谷歌,当然失效了。
translate() { wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=${2:-en}|${3:-zh}" | sed -E -n 's/[[:alnum:]": {}]+"translatedText":"([^"]+)".*/\1/p'; return 0; }
为了方便自己学习和练手,修改成金山词典的。苦于半桶水的水平,反复用了好些管道和sed进行过滤和排版,最后勉强可用。写出来交流交流,让各路高手给小弟指正一下:
translate() { echo echo "${1}:" wget -qO- "http://www.iciba.com/$1"|\ sed -n '/"prons"/,/"net_paraphrase"/p'|\ sed -e 's/<[^>]*>//g' -e 's/[[:space:]]//g'|\ tr -d '\n'|\ sed -e 's/]/]\t/' -e 's/[a-z]\{1,\}\./\n&/g' echo echo return 0; }
把这段函数放到~/.bashrc里面,重开一个终端就可以用了:
$ translate computer computer: 英[kmpju:t(r)] 美[kmpjut] n.(电子)计算机,电脑 $
这个地方自己一直不是很满意,感觉总有更简洁的方法来实现:
sed -n '/"prons"/,/"net_paraphrase"/p' //定位需要的代码块,我选择从读音到简单词义部分 sed -e 's/<[^>]*>//g' -e 's/[[:space:]]//g' //删除所有<...>的HTML标记和空格 tr -d '\n' //删除所有换行,把文字都排成一行 sed -e 's/]/]\t/' -e 's/[a-z]\{1,\}\./\n&/g' //音标之间加TAB,词性前加换行
新增用海词词典的,速度稍快一些:
ts() { echo echo "${1}:" wget -qO- "http://dict.cn/$1"|\ sed -n '/"phonetic"/,/"padding-top:/p'|\ sed -e 's/<[^>]*>//g' -e 's/[[:space:]]//g'|\ tr -d '\n'|\ sed -e 's/]/]\t/' -e 's/[a-z]\{1,\}\./\n&/g' echo echo return 0; }
转载于:https://blog.51cto.com/willron/1574834