Skip to Content

自动翻译desktop文件的bash脚本

labrador 的头像
下面的脚本tranlsate使用Google Translate将一个字符串做英汉互译。
#!/bin/sh

urlencode() {
    sed '
s/%/%25/g
s/ /%20/g
s/ /%09/g
s/!/%21/g
s/"/%22/g
s/#/%23/g
s/\$/%24/g
s/\&/%26/g
s/'\''/%27/g
s/(/%28/g
s/)/%29/g
s/\*/%2a/g
s/+/%2b/g
s/,/%2c/g
s/-/%2d/g
s/\./%2e/g
s/\//%2f/g
s/:/%3a/g
s/;/%3b/g
s//%3e/g
s/?/%3f/g
s/@/%40/g
s/\[/%5b/g
s/\\/%5c/g
s/\]/%5d/g
s/\^/%5e/g
s/_/%5f/g
s/`/%60/g
s/{/%7b/g
s/|/%7c/g
s/}/%7d/g
s/~/%7e/g
s/\t/%09/g
'
}

htmldecode() {
    sed '
s/'/'\''/g
s/&lt;/</g
s/&gt;/>/g
s/&amp;/&/g
'
}

translate() {
    if [ "$1" = "`echo "$1" | strings`" ]; then
	LANGPAIR="sl=en&tl=zh-CN"
    else
	LANGPAIR="sl=zh-CN&tl=en"
    fi
    TEXT="`echo "$1" | urlencode`"
    wget "http://www.google.com/translate_t?$LANGPAIR" \
	--header="Content-Type: application/x-www-form-urlencoded" \
	--header="User-Agent: Mozilla/5.0" \
	--post-data="text=$TEXT" \
	--quiet \
	--output-document - |
    grep -o '<div id=result_box dir="ltr">[^<]*</div>' |
    sed 's/<\/\?div[^>]*>//g' |
    htmldecode
}
自动翻译desktop文件,其中调用了上面的translate脚本
#!/bin/sh

. translate

TOLANG="zh-CN"

for i in "$@"; do
    TEXT="`sed -n '/^Name=/ { s/^Name=//; p }' "$i"`"
    TRANS="`sed -n '/^Name\['$TOLANG'\]=/ { s/^Name[^=]\+=//; p }' "$i"`"
    [ -z "$TRANS" ] && TRANS="${TEXT%% *} `translate "${TEXT#* }"`"
    TRANS="`Xdialog --wmclass "gtkdialog2" --fill --title "Translate $i" --stdout --inputbox "Original: $TEXT\n\nTranslation: $TRANS\n\nYour translation:" 0 0 "$TRANS"`"
    if [ $? -eq 0 ]; then
	sed -i '/^Name\['$TOLANG'\]=/ d' "$i"
	echo "Name[${TOLANG}]=$TRANS" >>$i
    fi
done   

发表新评论

  • 你可以在文本中使用BBCode标记语言。 URL会自动被转为链接。

更多关於格式化选项的信息

CAPTCHA
请验证您是否是机器人。
Image CAPTCHA
Enter the characters shown in the image.