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 come into contact with a larger world, and you will find more information. Especially for programmers, good programming materials come from English documents. Many of the translated versions in China are so different from the original ones that they are even wrong.
Although there are a lot of translation software now, it's a great sense of achievement to write a small python program by yourself. Even with today's code, you can develop your own small translation software.
Tao Dictionary interface
Today's translation program is implemented by means of an interface of Daoist translation. The logic of the program is very simple, that is to use the Daoist translation, take the content to be translated as a parameter, and send it to the corresponding url. Then we can get the corresponding translation results by returning a json data through the server with Tao.
Program call results
Start the program in the terminal input you want to translate the content, can be translated into English, can also be translated into English. For example, type "Koc is the most handsome! "
Corresponding input English can also be translated into Chinese.
Program code
The program code is very simple. I have comments in the corresponding code.
import json
import requests
#Translation function, what word needs to translate
def translate(word):
#Youdao dictionary api
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
#Parameters of the transmission, 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 this dictionary is the content sent to the Youdao dictionary server
response = requests.post(url, data=key)
#Judge whether the server is successful
if response.status_code == 200:
#And then the corresponding results
return response.text
else:
print("Failed to call Youdao dictionary")
#Corresponding failure returns null
return None
def get_reuslt(repsonse):
#Load the returned result into JSON format through json.loads
result = json.loads(repsonse)
print ("The words entered are:%s" % result['translateResult'][0][0]['src'])
print ("The translation results are as follows:%s" % result['translateResult'][0][0]['tgt'])
def main():
print("This program calls Youdao Dictionary API Translation can achieve the following results:")
print("foreign language-->Chinese")
print("Chinese-->English")
word = input('Please input the words or sentences you want to translate:')
list_trans = translate(word)
get_reuslt(list_trans)
if __name__ == '__main__':
main()
This article starts with the official account of "sea of sea". The official account answers "1024" and receives 2018 of the latest python courses free of charge.