It takes about 4.2 minutes to read the text.
Nowadays, more and more attention is paid to English ability. If you know English, you will get in touch with the larger world and you will find more information. For programmers in particular, good programming material comes from English documentation. Those domestic translations of the version, there are a lot of content with the original too much, even irrelevant.
There are a lot of translation software out there, but it can be very rewarding to write your own Python mini-program. You can even build your own small translation software with today’s code.
Interface of Youdao Dictionary
Today’s translation program is borrowed from youdao translation interface to achieve. The logic of the program is very simple, that is, youdao translation is used to transfer the content to be translated as a parameter to the corresponding URL. Then youdao server returns a JSON data, we can get the corresponding translation results.
Program call result
Start the program in the terminal input you want to translate the content, can be translated from Chinese to English, also can be translated from English to Chinese. For example, type “Koc is the most handsome!” .
The corresponding input from English can also be translated into Chinese.
The program code
The program code is very simple, and I have comments in the corresponding code.
import json
import requests
# Translation function, Word needs to translate the content
def translate(word):
# Youdao Dictionary API
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
# Transfer parameters, where I is the content to be translated
key = {
'type': "AUTO".'i': word,
"doctype": "json"."version": "2.1"."keyfrom": "fanyi.web"."ue": "UTF-8"."action": "FY_BY_CLICKBUTTON"."typoResult": "true"
}
# key is the dictionary that is sent to the Youdao Dictionary server
response = requests.post(url, data=key)
Check whether the server succeeded
if response.status_code == 200:
# and the corresponding result
return response.text
else:
print("Failed to call Youdao Dictionary")
Return null on corresponding failure
return None
def get_reuslt(repsonse):
Loads the result in JSON format with json.loads
result = json.loads(repsonse)
print ("The input word is: %s" % result['translateResult'] [0] [0] ['src'])
print ("%s" % result['translateResult'] [0] [0] ['tgt'])
def main():
print("This program calls the API of Youdao Dictionary for translation, which can achieve the following effects:")
print("Foreign Languages --> Chinese")
print("Chinese --> English")
word = input('Please enter the word or sentence you want translated:')
list_trans = translate(word)
get_reuslt(list_trans)
if __name__ == '__main__':
main()
Copy the code
This article was first published on the public account “Crazy Sea”. The public account “1024” is free to receive the latest Python tutorial 2018.