欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

用Python編寫一個基于終端的實現(xiàn)翻譯的腳本

 更新時間:2015年04月24日 15:52:22   作者:C Wong  
這篇文章主要介紹了用Python編寫一個基于終端的實現(xiàn)翻譯的腳本,代碼基于Python2.x,需要的朋友可以參考下

為什么寫這個程序,為什么不給這個程序配備gui?原因很簡單,因為我是一個命令行控,Linux習(xí)慣了不習(xí)慣了鼠標(biāo),總覺得點著不如敲命令快,各位在看這篇文章就說明和本人有相同的愛好.這個用python寫的翻譯工具是通過google來實現(xiàn)的,由于google返回的數(shù)據(jù)不是很規(guī)范(或者說我沒有找到規(guī)律),現(xiàn)在前三項能正常顯示(源詞,翻譯結(jié)果,和漢語拼音).下面的詞性和其他釋義可能不同,見諒,望大神可以指點下小弟和幫小弟完善,這里趕緊不盡.

好了不費話了,下面放代碼:

#!/usr/bin/env python
# -*-coding:utf8 -*-
'''
#=============================================================================
#   FileName: translate.py
#     Desc: To translate with zh to en or en2zh
#    Author: cold
#    Email: wh_linux@126.com
#   HomePage: http://www.linuxzen.com
#   Version: 0.0.1
#  LastChange: 2012-04-23 23:04:08
#   History:
#=============================================================================
'''

import urllib
import urllib2
from sys import argv,exit
import re

# 顯示幫助信息
def helpinfo():
print '''
Usage: pytran {zh2en|en2zh} content
'''
# 格式化輸出
def formatresult(result,srclang):
resu = result.split('[[')
if (srclang=='en2zh' or srclang == 'zh2en'):
firstre = resu[1].replace('[','').replace(']','').split('"')
print '源詞:',firstre[3]
print '結(jié)果:',firstre[1]
if (srclang=='zh2en'):
piny = firstre[7]
else:
piny = firstre[5]
print '拼音:',piny
if(srclang=='zh2en'):
secresu=resu[2].replace('"','').split('[')
else:
secresu = resu[2].replace('"', '').split('[')
print '詞性:',secresu[0].replace(',','')
print '其他釋義:'
for i in ''.join(secresu[1].split(']')).split(','):
print i

# 獲取命令行參數(shù)
try:
srclang = argv[1]
except:
helpinfo()
exit(1)
try:
cont = argv[2]
except:
helpinfo()
exit(2)

# 判斷翻譯目標(biāo)語言用來確定傳送參數(shù)
if(srclang == 'zh2en'):
data=urllib.urlencode({'client':'t', 'text':cont,
'hl':'zh-CN','tl':'en',
'multires':'1','prev':'btn',
'ssel':'0','sc':'1'})
elif(srclang == 'en2zh'):
data=urllib.urlencode({'client':'t', 'text':cont,
'hl':'zh-CN', 'sl':'en','tl':'zh-CN',
'multires':'1', 'prev':'btn',
'ssel':'0','sc':'1'})
else:
helpinfo()

# 打開google翻譯內(nèi)容
url = 'http://translate.google.cn/translate_a/t'
req =urllib2.Request(url,data)
req.add_header("User-Agent", "Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)")
fd = urllib2.urlopen(req)
result = fd.read()

# 格式化輸出
formatresult(result, srclang)
fd.close()

為了更方便的使用我們把這個腳本命名位pytranslate,放到/usr/bin下,并賦予執(zhí)行權(quán)限:

chmod +x /usr/bin/pytranslate

然后我們就可以使用它進(jìn)行翻譯了: 翻譯英文到中文:

pytranslate en2zh extent
源詞: extent
結(jié)果: 程度
拼音: Chéngdù
詞性: 名詞
其他釋義:
程度
范圍
幅度
規(guī)模
度
地步
廣度
長度
面
長短
份兒
界
en
翻譯中文到英文
pytranslate zh2en 中國
源詞: 中國
結(jié)果: China
拼音: Zhōngguó
詞性: 名詞
其他釋義:
China
zh-CN

好吧相信聰明的你肯定發(fā)現(xiàn)如何使用了這里就不羅嗦了.

相關(guān)文章

最新評論