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实现文本界面网络聊天室

Hello大家好,今天说一下python的socket编程,基于python的socket通信的文本框网络聊天 首先,实验环境: 一个云服务器(我们这里是用的阿里云,大家将就自己的条件吧...

Python实现将字符串的首字母变为大写,其余都变为小写的方法

利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。 思路:使用capitalize()函数将字符串的首字母转为大写,其余变为小写 L1 = ['A...

python 读取鼠标点击坐标的实例

读取鼠标点击坐标,包括点下去和抬起来的坐标,注意不要在命令行点,可能会出问题 import pythoncom, pyHook def onMouseEvent(event):...

Python探索之pLSA实现代码

pLSA(probabilistic Latent Semantic Analysis),概率潜在语义分析模型,是1999年Hoffman提出的一个被称为第一个能解决一词多义问题的模型,...

解决Python3 被PHP程序调用执行返回乱码的问题

因为有一部分程序是 Python 写的,所以需要 PHP 调用 Python 程序返回数据,使用 exec 返回的是乱码 $data = "Geek程序员" $get = exec(...