1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import os import re import sys import requests import click
def output(): output=os.path.dirname(__file__)+"\\output" if not os.path.exists(output): os.makedirs(output) return output+'\\'
def translate(sentence): payload={ 'i': sentence, 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': '15765004769734', 'sign': '4d0e06d29b69a27b13b5c6356b64abeb', 'ts': '1576500476973', 'bv': '5575008ba9785f184b106838a72d6536', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTlME' } a=requests.post('http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule',data=payload) result=a.json() f=open(output()+sentence[0]+'...'+sentence[-1]+'.txt','w',encoding='utf-8') if result['translateResult'][0][0]['tgt']!=sentence: print('翻译结果:'+result['translateResult'][0][0]['tgt'],file=f) print('翻译结果:'+result['translateResult'][0][0]['tgt'],file=sys.stdout) else: print('翻译结果:'+result['translateResult'][0][0]['src'],file=f) print('翻译结果:'+result['translateResult'][0][0]['src'],file=sys.stdout)
@click.command() @click.option('--file',default='default',help='the text to be translated')
def main(file): if(file=='default'): use=''' Usage: YouDaotranslate.py [OPTIONS]
Options: --file TEXT the text to be translated --help Show this message and exit. ''' print(use) sentence=input('输入要翻译的内容:') translate(sentence) else: if not os.path.exists(file): print('指定文件不存在!') else: sentence=open(file,'r',encoding='utf-8').read() translate(sentence) print("翻译结果已保存至output/"+sentence[0]+'...'+sentence[-1]+'.txt')
if __name__=='__main__': main()
|