程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Test the effect of using Python to complete Chinese English translation

編輯:Python

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

Chinese English translation Objective record
Contents
Proper translation Baidu translation Google online translation There is an online translation Translation assistant Modification method Use effect Test summary

 

§01 in 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 .

1.1 Proper translation

Reference link :https://segmentfault.com/a/1190000015643320

1.1.1 Code implementation

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()

1.1.2 test result

Test output :

 The entered word is :distortion
The translation result is : The distortion

1.1.3 Usage restriction

Every hour 1000 Access restrictions , If you exceed it, you will be banned !!!!

1.1.4 Encapsulate as a function

""" 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!"""

1.2 Baidu translation

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 .

1.2.1 Test code

""" 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!")

1.2.2 test result

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 appidsecretkey 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 .

1.3 Google online translation

Reference: https://github.com/terryyin/translate-python

Every day 1000 Translation limit of words , Not suitable for translation of a large number of words

1.3.1 Test code

from translate import Translator
translator= Translator(to_lang="zh")
translation = translator.translate("Steelmaking")
print(translation)

1.3.2 Running results

 steel-making

1.3.3 Existing problems

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 ”

1.4 There is an online translation

Reference: https://pypi.org/project/pytranslator/

1.4.1 Install package

First, you need to install the corresponding software package : pytranslator

pythom -m pip install pytranslator

▲ chart 1.4.1 pytranslator

1.4.2 Test code

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'

1.4.3 Instructions

Project name :

&emsp;&emsp;pytranslator

Example :

&emsp;&emsp;import pytranslator
&emsp;&emsp;youdao = pytranslator.youdao("YOUR_KEY","YOU_KEY_FROM")
&emsp;&emsp;youdao.trans("Help")

Update log :

&emsp;&emsp;==============
&emsp;&emsp; Time : 2017/02/20
&emsp;&emsp; author : Wang Yihang
&emsp;&emsp; describe : Open source to pypi
&emsp;&emsp; edition : 1.3.6
&emsp;&emsp;==============

Principle that :

&emsp;&emsp; Use Youdao translation to open API Carry out Chinese English Translation
&emsp;&emsp; Will be returned by Youdao server JSON The data is parsed and packaged into a function for calling

Environmental requirements :

&emsp;&emsp;python 2.x
&emsp;&emsp;requests

Download and install :
1. install with pip

&emsp;&emsp;sudo pip install pytranslator

2. install with source code

&emsp;&emsp;git clone https://git.coding,net/yihangwang/PyTranslator.git
&emsp;&emsp;cd ./PyTranslator
&emsp;&emsp;sudo python setup.py install

Usage method :

&emsp;&emsp;1. [ Apply for Youdao translation Key](http://fanyi.youdao.com/openapi?path=data-mode)
&emsp;&emsp; You need to fill in the email and application name , Then you will receive KEY and KEY_FROM
&emsp;&emsp;2. Introduction package pytranslator
&emsp;&emsp;3. According to the first 1 Received in the next email KEY and KEY_FROM call youdao Class constructor
&emsp;&emsp;4. After the call is successful , It can be adjusted youdao Class trans To return
&emsp;&emsp; The entry parameter is the string that needs to be translated , Can automatically recognize Chinese and English

TODO :

&emsp;&emsp;1. Open more interfaces ( Closer to Youdao API Various functions provided )
&emsp;&emsp;2. Save the results locally , Reduce the pressure on the server when users search for it many times
&emsp;&emsp;3. Chinese English translation function
&emsp;&emsp;4. Automatic completion function
&emsp;&emsp;5. Phrase query function
&emsp;&emsp;6. Whole sentence translation function

1.4.4 apply KEY

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

 

§02 double Translation assistant


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 .

2.1 Modification method

2.1.1 Use the syntax

utilize :

?>word1 word 2

Finish right word1、 word 2 Query for .

2.1.2 Realization way

(1) Command parsing part

 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()

(2) Add corresponding function

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']))

2.2 Use effect

? possibility China

 possibility --> possibility
China --> China
python --> python
beauty --> beautiful
command --> command
Data interface --> Data interface

 

※ measuring Try to summarize ※


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 :

  • PYTHON Realize automatic translation between Chinese and English

● Related chart Links :

  • chart 1.4.1 pytranslator
  • chart 1.4.2 Youdao translation corresponds to API Explain the interface

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved