python3使用urllib示例取googletranslate(谷歌翻译)

yipeiwu_com6年前Python基础

复制代码 代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File Name : gt1.py
# Purpose :
# Creation Date : 1390366260
# Last Modified : Wed 22 Jan 2014 06:14:11 PM CST
# Release By : Doom.zhou


import urllib.request
import sys

typ = sys.getfilesystemencoding()

def translate(querystr, to_l="zh", from_l="en"):
    '''for google tranlate by doom
    '''
    C_agent = {'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.165063 Safari/537.36 AppEngine-Google."}
    flag = 'class="t0">'
    tarurl = "http://translate.google.com/m?hl=%s&sl=%s&q=%s \
        " % (to_l, from_l, querystr.replace(" ", "+"))
    request = urllib.request.Request(tarurl, headers=C_agent)
    page = str(urllib.request.urlopen(request).read().decode(typ))
    target = page[page.find(flag) + len(flag):]
    target = target.split("<")[0]
    return target

print(translate("Hello world"))

相关文章

python中使用psutil查看内存占用的情况

有的时候需要对python程序内存占用进行监控,这个时候可以用到psutil库,Anaconda中是自带的,如果import出错,可以用pip install psutil(安装在pyt...

python 将md5转为16字节的方法

python的hashlib库中提供的hexdigest返回长度32的字符串。 直接通过digest返回的16字节,有不可打印字符。 问题来了,因为md5sum是128bit,也就是16...

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

本文实例讲述了Python实现的登录验证系统。分享给大家供大家参考,具体如下: 小型登录注册验证系统 一、概述 ​ 使用Redis+MySQL数据库实现一个小型的登录注册验证...

Python数据可视化实现正态分布(高斯分布)

Python数据可视化实现正态分布(高斯分布)

正态分布(Normal distribution)又成为高斯分布(Gaussian distribution) 若随机变量X服从一个数学期望为、标准方差为的高斯分布,记为: 则其概...

mac下给python3安装requests库和scrapy库的实例

众所周知,Mac自带python2,但无奈我们想使用新版本,因此我们需要安装python3 安装python3我使用了homebrew,网上也有很多教程,这里不多说 为python3安装...