python百度翻译urllib_【Python】Python的urllib、urllib2模块调用“百度翻译”API进行...

1.问题描述在文本数据处理时,经常回出现文本中各种语言的混杂情况,包括:英文、日语、俄语、法语等,需要将不同语种的语言批量翻译成中文进行处理。可以通过Py

1.问题描述

在文本数据处理时,经常回出现文本中各种语言的混杂情况,包括:英文、日语、俄语、法语等,需要将不同语种的语言批量翻译成中文进行处理。可以通过Python直接调用百度提供的翻译API进行批量的翻译。

百度翻译API详细文档见:百度翻译API文档

2.问题解决

开发环境:Linux

将文本中的中文和非中文进行分离,,对非中文的部分进行翻译。

Python的代码如下:

#!/usr/bin/python

#-*- coding:utf-8 -*-

import sys

reload(sys)

sys.setdefaultencoding("utf8")

import re

import json

import langid

import urllib

from urllib2 import Request, urlopen, URLError, HTTPError

def translate(inputFile, outputFile):

fin = open(inputFile, 'r')

fout = open(outputFile, 'w')

for eachLine in fin:

line = eachLine.strip()

quoteStr = urllib.quote(line)

url = '?client_id=WtzfFYTtXyTocv7wjUrfGR9W&q=' + quoteStr + '&from=auto&to=zh'

try:

resultPage = urlopen(url)

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

js = None

try:

js = json.loads(resultJason)

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

if __name__ == '__main__':

translate(sys.argv[1], sys.argv[2])

3.注意

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值