Jane Medium : Tested the effect of some online translation tools , utilize Proper translation It is convenient to confirm common new words . about TEASOFT Software PYTHON Function reconstruction , given ?> Translation mode function .
key word
: online translation , Chinese English translation
stay Chinese English translation is often used in daily work . Use a lot of English dictionary software based on Internet ( such as YouDao) Although available , But sometimes I still hope that the mechanism can be in TEASOFT Complete the translation of words in the software environment , Or batch translation of many words . Here are some tests based on PYTHON Environment Chinese English translation software .
The following method is from CSDN post PYTHON Realize automatic translation between Chinese and English The scheme sorted out in , Let's have a preliminary test .
Reference link :https://segmentfault.com/a/1190000015643320
from headm import * # =
import json
import requests
def translate(word):
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
key = {
'type': "AUTO",
'i': word,
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"ue": "UTF-8",
"action": "FY_BY_CLICKBUTTON",
"typoResult": "true"
}
response = requests.post(url, data=key)
if response.status_code == 200:
return response.text
else:
print(" Youdao dictionary call failed ")
return None
def get_reuslt(repsonse):
result = json.loads(repsonse)
printf (" The entered word is :%s" % result['translateResult'][0][0]['src'])
printf (" The translation result is :%s" % result['translateResult'][0][0]['tgt'])
def main():
word = 'distortion'
list_trans = translate(word)
get_reuslt(list_trans)
if __name__ == '__main__':
main()
Test output :
The entered word is :distortion
The translation result is : The distortion
Every hour 1000 Access restrictions , If you exceed it, you will be banned !!!!
""" Proper translation API Call function of ( Encapsulated as a function, use )"""
import json
import requests
import re
def translator(str):
""" input : str String to translate output:translation Translated string """
# API
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
# Parameters of transmission , i For the content to be translated
key = {
'type': "AUTO",
'i': str,
"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 Youdao dictionary server
response = requests.post(url, data=key)
# Judge whether the server is successful
if response.status_code == 200:
# adopt json.loads Load the returned results into json Format
result = json.loads(response.text)
# print (" The entered word is :%s" % result['translateResult'][0][0]['src'])
# print (" The translation result is :%s" % result['translateResult'][0][0]['tgt'])
translation = result['translateResult'][0][0]['tgt']
return translation
else:
print(" Youdao dictionary call failed ")
# The corresponding failure returns null
return None
""" Youdao translation function DONE!"""
reference :https://blog.csdn.net/baidu_33718858/article/details/83306851
The latest Baidu translation API Charging standard : If the number of characters translated in the current month ≤2 One million , Free in the month ; If more than 2 Million characters , according to 49 element / Million characters to pay the excess of the month .
""" official Python Access to baidu translation API test Demo( There are changes , official DEMO It's a bit out of date ,Python There are some changes in the package )"""
import httplib2
import urllib
import random
import json
from hashlib import md5
appid = '*********' # Yours appid
secretKey = '********' # Your key
httpClient = None
myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
q = 'apple' # Words to be translated
fromLang = 'en' # Source language
toLang = 'zh' # The translation of language
salt = random.randint(32768, 65536)
# Signature
sign = appid+q+str(salt)+secretKey
m1 = md5()
m1.update(sign.encode(encoding = 'utf-8'))
sign = m1.hexdigest()
# myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
myurl = myurl+'?q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&appid='+appid+'&salt='+str(salt)+'&sign='+sign
try:
h = httplib2.Http('.cache')
response, content = h.request(myurl)
if response.status == 200:
print(content.decode('utf-8'))
print(type(content))
response = json.loads(content.decode('utf-8')) # loads take json The data is loaded as dict Format
print(type(response))
print(response["trans_result"][0]['dst'])
except httplib2.ServerNotFoundError:
print("Site is Down!")
After running , The following error always occurs :
{"error_code":"52003","error_msg":"UNAUTHORIZED USER"}
<class 'bytes'>
<class 'dict'>
Traceback (most recent call last):
File "D:\Temp\TEMP0001\test2.PY", line 45, in <module>
print(response["trans_result"][0]['dst'])
KeyError: 'trans_result'
The only question here : It's one of them appid、secretkey What exactly needs to be filled in ? Is it necessary to apply for the corresponding application account ? I use my baidu account , The test still doesn't work .
Reference: https://github.com/terryyin/translate-python
Every day 1000 Translation limit of words , Not suitable for translation of a large number of words
from translate import Translator
translator= Translator(to_lang="zh")
translation = translator.translate("Steelmaking")
print(translation)
steel-making
Although the translation process is relatively simple , But when translating from Chinese to English , There is a high probability of error .
from translate import Translator
translator= Translator(to_lang="english")
translation = translator.translate(" data ")
print(translation)
The output is still “ data ”
Reference: https://pypi.org/project/pytranslator/
First, you need to install the corresponding software package : pytranslator
pythom -m pip install pytranslator
▲ chart 1.4.1 pytranslator
import pytranslator
youdao = pytranslator.youdao('YOUR_KEY','YOU_KEY_FROM')
youdao.trans('help')
however , There was an error running :
Traceback (most recent call last):
File "D:\Temp\TEMP0001\test4.PY", line 12, in <module>
youdao = pytranslator.youdao('YOUR_KEY','YOU_KEY_FROM')
AttributeError: module 'pytranslator' has no attribute 'youdao'
Project name :
  pytranslator
Example :
  import pytranslator
  youdao = pytranslator.youdao("YOUR_KEY","YOU_KEY_FROM")
  youdao.trans("Help")
Update log :
  ==============
   Time : 2017/02/20
   author : Wang Yihang
   describe : Open source to pypi
   edition : 1.3.6
  ==============
Principle that :
   Use Youdao translation to open API Carry out Chinese English Translation
   Will be returned by Youdao server JSON The data is parsed and packaged into a function for calling
Environmental requirements :
  python 2.x
  requests
Download and install :
1. install with pip
  sudo pip install pytranslator
2. install with source code
  git clone https://git.coding,net/yihangwang/PyTranslator.git
  cd ./PyTranslator
  sudo python setup.py install
Usage method :
  1. [ Apply for Youdao translation Key](http://fanyi.youdao.com/openapi?path=data-mode)
   You need to fill in the email and application name , Then you will receive KEY and KEY_FROM
  2. Introduction package pytranslator
  3. According to the first 1 Received in the next email KEY and KEY_FROM call youdao Class constructor
  4. After the call is successful , It can be adjusted youdao Class trans To return
   The entry parameter is the string that needs to be translated , Can automatically recognize Chinese and English
TODO :
  1. Open more interfaces ( Closer to Youdao API Various functions provided )
  2. Save the results locally , Reduce the pressure on the server when users search for it many times
  3. Chinese English translation function
  4. Automatic completion function
  5. Phrase query function
  6. Whole sentence translation function
You can see , During the previous use , Fill in KEY,KEY_FROM No application was made . Need to pass through Apply for Youdao translation Key Get the corresponding KEY,KEY_FROM.
However, there are some problems in the process of login and account application on the back page . Give up for the time being .
▲ chart 1.4.2 Youdao translation corresponds to API Explain the interface
through Pass the previous test , You can see that the effect of using Youdao translation is still good . Now for cdtm To transform , Form a translation shortcut .
utilize :
?>word1 word 2
Finish right word1、 word 2 Query for .
elif sys.argv[1][0] == '>' or sys.argv[1][0] == '》':
strall = sys.argv[1:]
strall[0] = strall[0][1:]
for word in strall:
list_trans = translate(word)
get_reuslt(list_trans)
exit()
import json
import requests
def translate(word):
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
key = {
'type': "AUTO",
'i': word,
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"ue": "UTF-8",
"action": "FY_BY_CLICKBUTTON",
"typoResult": "true"
}
response = requests.post(url, data=key)
if response.status_code == 200:
return response.text
else:
return None
def get_reuslt(repsonse):
result = json.loads(repsonse)
printf ("%s --> %s" %(result['translateResult'][0][0]['src'], result['translateResult'][0][0]['tgt']))
? possibility China
possibility --> possibility
China --> China
python --> python
beauty --> beautiful
command --> command
Data interface --> Data interface
measuring Try the effect of some online translation tools , utilize Proper translation It is convenient to confirm common new words . about TEASOFT Software PYTHON Function reconstruction , given ?> Translation mode function .
■ Links to related literature :
● Related chart Links :