欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python翻译软件实现代码(使用google api完成)

程序员文章站 2022-09-09 08:09:51
复制代码 代码如下:# -*- coding: utf-8 -*- import httplibfrom urllib import urlencodeimport re...

复制代码 代码如下:

# -*- coding: utf-8 -*-
import httplib
from urllib import urlencode
import re

def out(text):
    p = re.compile(r'","')
    m = p.split(text)
    print m[0][4:].decode('utf-8').encode('gbk')

if __name__=='__main__':
    while true:
        word=raw_input('input the word you want to search:')
        text=urlencode({'text':word})
        h=httplib.http('translate.google.cn')
        h.putrequest('get', '/translate_a/t?client=t&hl=zh-cn&sl=en&tl=zh-cn&ie=utf-8&oe=utf-8&'+text)
        h.endheaders()
        h.getreply()
        f = h.getfile()
        lines = f.readlines()
        out(lines[0])
        f.close()

 haskell版

 

复制代码 代码如下:

 module main where

import network.http
import text.regex.posix

main = do
    putstrln "input the word you want to search:"
    word <- getline
    handle <- simplehttp (getrequest $ "http://translate.google.cn/translate_a/t?client=t&hl=zh-cn&sl=en&tl=zh-cn&ie=utf-8&oe=utf-8&" ++ (text word))
    content <- getresponsebody handle
    let match = (content =~ "\",\""::(string,string,string))
    putstrln $ drop 4 $ first match
    main

text word = urlencodevars [("text",word)]

first::(string,string,string)->string
first (x,_,_) = x



作者:hevienz