Python 翻译文章 txt文件

#!/usr/bin/python
#-*- coding:utf-8 -*-
import os  
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import random
import md5
import json                                                                     #导入json模块
import urllib                                                                   #导入urllib模块
from urllib2 import Request, urlopen, URLError, HTTPError                       #导入urllib2模块

def translate(inputFile, outputFile):
	fin = open(inputFile, 'r')                                              #以读的方式打开输入文件
	fout = open(outputFile, 'w')                                            #以写的方式代开输出文件
        appid = '2027074000067214'
        secretKey = 'LCgis7L17X56qykeTgB'
        myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
        fromLang = 'auto'
        toLang = 'fra'
        salt = random.randint(32761, 65226)
	for eachLine in fin:                                                    #按行读入文件
		line = eachLine.strip()                                         #去除每行首尾可能的空格等
		q = line                                #将读入的每行内容转换成特定的格式进行翻译
		sign = appid+q+str(salt)+secretKey
                m1 = md5.new()
                m1.update(sign)
                sign = m1.hexdigest()
                myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
		url = myurl
		try:
			resultPage = urlopen(url)                               #调用百度翻译API进行批量翻译
		except HTTPError as e:
			print('The server couldn\'t fulfill the request.')
			print('Error code: ', e.code)
		except URLError as e:
			print('We failed to reach a server.')
			print('Reason: ', e.reason)
		except Exception, e:
			print 'translate error.'
			print e
			continue

		resultJason = resultPage.read().decode('utf-8')                #取得翻译的结果,翻译的结果是json格式
		js = None
		try:
			js = json.loads(resultJason)                           #将json格式的结果转换成Python的字典结构
		except Exception, e:
			print 'loads Json error.'
			print e
			continue
	
		key = u"trans_result" 
		if key in js:
			dst = js["trans_result"][0]["dst"]                     #取得翻译后的文本结果
			outStr = dst
		else:
			outStr = line                                          #如果翻译出错,则输出原来的文本

		fout.write(outStr.strip().encode('utf-8') + '\n')              #将结果输出
		
	fin.close()
	fout.close()

#获取目标文件夹的路径  
meragefiledir = os.getcwd()+'\\InFiles'
meragefiledir2 = os.getcwd()+'\\OutFiles'
#获取当前文件夹中的文件名称列表  
filenames=os.listdir(meragefiledir)  
  
#先遍历文件名  多个txt文章文件
for filename in filenames:  
    filepath=meragefiledir+'\\'
    filepath=filepath+filename
    filepath2=meragefiledir2+'\\'+filename
    #遍历单个文件,读取行数
    translate(filepath,filepath2)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值