美文网首页
简单爬虫进行拼音转汉字

简单爬虫进行拼音转汉字

作者: 小木胆 | 来源:发表于2017-04-26 10:04 被阅读0次

论坛里面有人用想用搜索引擎进行拼音转汉字。

目前已经有了百度的代码,就是要修改为google。

很简单的东西,用urllib2+beautifulsoup就是分分钟的事情,但是考虑到这个哥们估计不会安装beautifulsoup,所以还是用re来解决:

#!/usr/bin/env python
# -*- coding: utf_8 -*-

import re
from urllib2 import Request, urlopen

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language':'en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4,ja;q=0.2',
    'Cache-Control':'max-age=0',
    'Connection':'keep-alive',
    'DNT':'1',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36',
}  
url_base = "https://www.google.co.jp/search?site=&source=hp&q=%s&oq=%s"

def getpage(url):
    response = urlopen(Request(url = url,headers = headers), timeout = 60) 
    return response.read()

def han(keyword):
    page = getpage(url_base % (keyword, keyword))
    result = re.findall('<a class="spell" href=.*?><em>(.*?)</em></a>', page) 
    ret = result[0] if len(result)>0 else ""
    return ret

def getwords(input_file):
    with open(input_file) as f:
        raw_text = f.readlines()
    return [i.strip() for i in raw_text]


if __name__ == "__main__":
    input_file  = '三拼四拼.txt'
    output_file = input_file.replace('.txt','_cn.txt')
    words = getwords(input_file)

    with open(output_file, 'w') as f:
        for word in words:
            cn = han(word)
            print '%s:%s\n'% (word, cn)
            f.write('%s:%s\n'% (word, cn))
    print '\n Done.'

相关文章

  • 简单爬虫进行拼音转汉字

    论坛里面有人用想用搜索引擎进行拼音转汉字。 目前已经有了百度的代码,就是要修改为google。 很简单的东西,用u...

  • Python 拼音汉字互转

    汉字转拼音:pypinyin拼音转汉字:Pinyin2Hanzi Python汉字转拼音-拼音转汉字的效率测评

  • python汉字转拼音

    场景说明 把中文汉字、转成汉语拼音,包括: 纯汉字转拼音 汉字里面加有字母转拼音 转加声调的拼音 转用数字表示声调...

  • 简单的汉字转拼音

    在开发中,面对通讯录或者联系人列表或者按字母分类这种开发需求,我们往往需要用到汉字转拼音,今天来介绍一个简单的汉字...

  • 发布 | 汉字转拼音工具

    通过查找汉字拼音库实现实时汉字转拼音的功能。 实现 加载汉字拼音对照文件pinyin.txt(4万+汉字拼音对照)...

  • 发布 | 汉字转拼音工具

    通过查找汉字拼音库实现实时汉字转拼音的功能。 实现 加载汉字拼音对照文件pinyin.txt(4万+汉字拼音对照)...

  • 汉字转拼音

    汉字转拼音有很多种方法, 在这里推荐一个在线的免费转拼音的网站。 点击访问??汉字转拼音??

  • python 实现汉字转拼音

    python 简单实现姓名汉字转拼音 eg:张三丰 ——> zhangsf郭靖 ——> guojing

  • 汉字转拼音

    几种方法 一种是建立一个拼音对应的汉字map,进行查表。一种是利用汉字编码,根据不同的区域求出拼音。 第一种的原...

  • 汉字转拼音

    不过要注意的是,有一些汉字为多音字,可能不太符合需求 具体的请参考这篇文章

网友评论

      本文标题:简单爬虫进行拼音转汉字

      本文链接:https://www.haomeiwen.com/subject/yzqizttx.html