Python实现句子翻译功能

yipeiwu_com6年前Python基础

初入Python,一开始就被她简介的语法所吸引,代码简洁优雅,之前在C#里面打开文件写入文件等操作相比Python复杂多了,而Python打开、修改和保存文件显得简单得多。

1、打开文件的例子:

 file=open('D:\\Python\\untitled\\Hello.txt','r',encoding='utf-8')
 data=file.read()
 print(data)
 file.close()

2、利用urllib库请求页面进行简单的翻译,请求百度翻译,将要翻译的内容当做参数传给百度,然后将结果赋值给参数,最后打印出来:

上代码:

import urllib.request
import urllib.parse
import json

content=input("=====请输入您要翻译的内容:=====\n")

url='http://fanyi.baidu.com/v2transapi'
data={}
data['from']='zh'
data['to']='en'
data['transtype']='translang'
data['simple_means_flag']='3'
data['query']=content
data=urllib.parse.urlencode(data).encode('utf-8')
response=urllib.request.urlopen(url,data)
html=response.read().decode('utf-8')
target=json.loads(html)
print("翻译结果为:%s"%(target['trans_result']['data'][0]['dst']))

实现效果如图:

实现代码很简单,下面再分享下urllib库的一些用法。

urlopen 语法

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)
#url:访问的网址
#data:额外的数据,如header,form data

用法

# request:GET
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

# request: POST
# http测试:http://httpbin.org/
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())

# 超时设置
import urllib.request
response = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())

import socket
import urllib.request
import urllib.error

try:
  response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
  if isinstance(e.reason,socket.timeout):
    print('TIME OUT')

响应

# 响应类型
import urllib.open
response = urllib.request.urlopen('https:///www.python.org')
print(type(response))
# 状态码, 响应头
import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

Request

声明一个request对象,该对象可以包括header等信息,然后用urlopen打开。

# 简单例子
import urllib.request
request = urllib.request.Requests('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

# 增加header
from urllib import request, parse
url = 'http://httpbin.org/post'
headers = {
  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
  'Host':'httpbin.org'
}
# 构造POST表格
dict = {
  'name':'Germey'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
response = request.urlopen(req)
print(response.read()).decode('utf-8')
# 或者随后增加header
from urllib import request, parse
url = 'http://httpbin.org/post'
dict = {
  'name':'Germey'
}
req = request.Request(url=url,data=data,method='POST')
req.add_hader('User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

总结

以上就是本文关于Python实现句子翻译功能的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

python+opencv实现的简单人脸识别代码示例

Python编程实现蚁群算法详解

python实现图片处理和特征提取详解

如有不足之处,欢迎留言指出。

相关文章

Python绘制堆叠柱状图的实例

Python绘制堆叠柱状图的实例

有个朋友要求帮忙绘制堆叠柱状图,查阅了一些文档之后也算是完成了,只是一个小demo,下面我就记录一下。 1.什么是堆叠柱状图 与并排显示分类的分组柱状图不同,堆叠柱状图将每个柱子进行分割...

python3.6 如何将list存入txt后再读出list的方法

python3.6 如何将list存入txt后再读出list的方法

今天遇到一个需求,就是将一个list文件读取后,存入一个txt配置文件。存入时,发现list文件无法直接存入,必须转为str模式。 但在读取txt时,就无法恢复成list类型来读取了(准...

对python中if语句的真假判断实例详解

说明 在python中,if作为条件语句,当if后面的条件参数为真时,则执行后面的语句块,反之跳过,为了深入理解if语句,我们需要知道if语句的真假判断方式。 示例 在python交互器...

Apache,wsgi,django 程序部署配置方法详解

Apache,wsgi,django 程序部署配置方法详解

本文实例讲述了Apache,wsgi,django 程序部署配置方法。分享给大家供大家参考,具体如下: 前面写过一篇文章,ngixn,uwsgi,django,python 环境配置,有...

对Python中9种生成新对象的方法总结

先定义一个类: class Point: def __init__(self, x, y): self.x = x self.y = y 下面我们使用9种方法来生...