用Python实现的中英文互译的小脚本

用Python实现的中英文互译的小脚本


刚开始学Python,觉得无聊,就想找个小程序练练手,那么问题来了,写什么呢?


想到本人英语撇,每次遇到单词都到有道词典网站上去翻译或者打开手机app翻译,觉得这样很麻烦,而且花费的时间又长,所以。。。


首先打开有道翻译的网站,然后审查元素,找到network,然后随便提交一个翻译信息,然后就瞪大眼珠子看着network,突然,一个post一闪而过


嘿嘿,逮到了,接下来,找到那个post的提交方式的那一项,点看,看他的数据是按照什么格式提交的,然后用Python仿照它的方式提交就好了


就下来直接上代码


#coding: utf-8
import urllib.request
import urllib.parse
import json

def get_data(words):
    data = {}
    data["type"] = "AUTO"
    data["i"] = words
    data["doctype"] = "json"
    data["xmlVersion"] = "1.8"
    data["keyfrom:fanyi"] = "web"
    data["ue"] = "UTF-8"
    data["action"] = "FY_BY_CLICKBUTTON"
    data["typoResult"] = "true"
    data = urllib.parse.urlencode(data).encode('utf-8')
    return data

def url_open(url, data):
    req = urllib.request.Request(url, data)
    req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36")
    response = urllib.request.urlopen(req)
    html = response.read()
    html = html.decode("utf-8")
    return html

def get_json_data(html):
    result = json.loads(html)
    result = result['translateResult']
    result = result[0][0]['tgt']
    return result

def main():
    words = input("please input words: ")
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict.top"

    data = get_data(words)
    html = url_open(url, data)
    result = get_json_data(html)
    print("The result: %s" % result)

if __name__ == "__main__":
    while True:
        main()

哈哈,以后翻译就方便多了,从此以后,就是用全英文的系统都不怕了,四六级就那么的过了

你可能感兴趣的:(Python)