python開發翻譯程式

來源:互聯網
上載者:User

標籤:python   程式   開發   

     多的不說,上代碼!!!


#!/usr/bin/env python
#coding: utf-8
import urllib,re,json

   
def input_content(url):                               #接收一個url(翻譯AIP)
   
while True:
       content = raw_input(‘請輸入翻譯內容:‘)           #使用者輸入的內容
       
if str.strip(content) == ‘‘:                  #如果使用者輸入的內容為空白
           
continue                                      #進入下一輪迴圈
       
elif content == ‘q‘ or content == ‘Q‘:        #如果輸入為Q或者q則退出程式
           
exit()
       print ‘\033[31m正在翻譯......\033[0m‘
       
url = url+content                               #將url和翻譯內容進行字串拼接
       
return url                                     #返回拼接完之後的url


def html(data):                                        #接收翻譯完之後的資料
   
for i in data:
       RE = re.compile(r‘translation.*?\]‘)             #定義Regex的匹配規則
       
list_lost = re.findall(RE,i)                  #匹配翻譯的內容
       
lost = list_lost[0].split(‘:‘)[1]              #取出匹配到的內容
       
result = json.loads(lost)                     #將取出的內容還原序列化
       
print result[0]+‘\n‘                               #列印翻譯的結果


if __name__ == ‘__main__‘:
   print ‘\033[33m輸入Q或q退出翻譯\033[0m\n‘              #高亮顯示退出資訊

   
while True:
       try:
           url = ‘http://fanyi.youdao.com/openapi.do?keyfrom=huyuanpy&key=902574943&type=data&doctype=json&version=1.1&q=‘
             
#調用有道的API介面
           
address = input_content(url)               #接收拼接之後的內容
           
data = urllib.urlopen(address)             #將資料傳給有道進行翻譯,得到翻譯之後的結果

           
html(data)                                 #將得到的資料進行格式化處理
       
except:
           print ‘\033[31m正在退出指令碼......\033[0m\n‘
           
exit()


本文出自 “自動化營運” 部落格,請務必保留此出處http://hongchen99.blog.51cto.com/12534281/1908047

python開發翻譯程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.