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

yipeiwu_com5年前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获取标准北京时间的方法

本文实例讲述了python获取标准北京时间的方法。分享给大家供大家参考。具体分析如下: 这段python代码主要通过www.beijing-time.org的官网上获取标准的北京时间,如...

python发布模块的步骤分享

python发布模块的步骤分享

1.为模块nester创建文件夹nester,其中包含:nester.py(模块文件): 复制代码 代码如下:"""这是"nester.py"模块,提供了一个名为print_lol()函...

详解python编译器和解释器的区别

高级语言不能直接被机器所理解执行,所以都需要一个翻译的阶段,解释型语言用到的是解释器,编译型语言用到的是编译器。 编译型语言通常的执行过程是:源代码——预处理器——编译器——目标代码——...

NumPy排序的实现

numpy.sort()函数 该函数提供了多种排序功能,支持归并排序,堆排序,快速排序等多种排序算法 使用numpy.sort()方法的格式为: numpy.sort(a,axis,k...

跟老齐学Python之一个免费的实验室

跟老齐学Python之一个免费的实验室

在学生时代,就羡慕实验室,老师在里面可以鼓捣各种有意思的东西。上大学的时候,终于有机会在实验室做大量实验了,因为我是物理系,并且,遇到了一位非常令我尊敬的老师——高老师,让我在他的实验室...