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

相关文章

详解django中使用定时任务的方法

今天介绍在django中使用定时任务的两种方式。 方式一: APScheduler 1)安装: pip install apscheduler 2)使用: from apsc...

Python调用百度根据经纬度查询地址的示例代码

如下所示: def locatebyLatLng(lat, lng, pois=0): ''' 根据经纬度查询地址 ''' items = {'location': str(...

python写入中英文字符串到文件的方法

本文实例讲述了python写入中英文字符串到文件的方法。分享给大家供大家参考。具体分析如下: python中如果使用系统默认的open方法打开的文件只能写入ascii吗,如果要写入中文需...

Python使用微信SDK实现的微信支付功能示例

本文实例讲述了Python使用微信SDK实现的微信支付功能。分享给大家供大家参考,具体如下: 最近一段时间一直在搞微信平台开发,v3.37版本微信支付接口变化贼大,所以就看着php的de...

解决新版Pycharm中Matplotlib图像不在弹出独立的显示窗口问题

解决新版Pycharm中Matplotlib图像不在弹出独立的显示窗口问题

官方说明链接: https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000736584-SciView-...