批量下载搜狗词库

来源:互联网 发布:机器视觉算法及应用 编辑:程序博客网 时间:2024/04/26 06:59

用于对知识的整理,方便后来者。

第一步: 用python爬取每个搜狗词库的基本信息,以及下载链接。

搜狗词库细胞库链接:http://pinyin.sogou.com/dict/cate/index/167

生成12个文件,用以下代码合并文件,并按照类别加入type字段,同时对官方推荐的词库进行标记。

#encoding=utf-8import sysdefaultencoding = 'utf-8'if sys.getdefaultencoding() != defaultencoding:    reload(sys)    sys.setdefaultencoding(defaultencoding)from codecs import openpath = 'C:\\Users\\ijiao\\Documents\\Crawler\\projects\\ana_for_word\\sougou dict\\sougouciku_total\\'filename_out = 'C:\\Users\\ijiao\\PycharmProjects\\fatedate\\jinqiao\\sogouciku\\sougouciku_list.txt'f_out = open(filename_out, 'w', 'utf-8', 'ignore')for f in (1,2,3,4,5,6,7,8,9,11,13,14):    if f == 1: type = u'城市信息'    elif f == 2: type = u'农林渔畜'    elif f == 3: type = u'工程应用'    elif f == 4: type = u'电子游戏'    elif f == 5: type = u'运动休闲'    elif f == 6: type = u'娱乐休闲'    elif f == 7: type = u'医学医药'    elif f == 8: type = u'艺术设计'    elif f == 9: type = u'社会科学'    elif f == 11: type = u'生活百科'    elif f == 13: type = u'自然科学'    elif f == 14: type = u'人文科学'    full_file = path + str(f) + '.csv'    f1= open(full_file,'r','gbk','ignore')    f1.readline()    for line_s in f1:        line =line_s.replace(u'【4字成语大全】 收录成语54,089个 (上)',u'【4字成语大全】(上)').replace(u'【4字成语大全】 收录成语54,089个(下)',u'【4字成语大全】(下)')        value = line.split(',')        name = value[0].replace('/','').replace('|','').replace('<','').replace('>','')        if name not in ('mu lan shi',\                        'script src=http:5.xsser2014.sinaap|1202"',\                        u'天堂Ⅱ全部技能名称',\                        u'颜文字 ㄟ( ▔',\                        u'创想云购',\                        u'欅坂46'):            popularity = value[1]            url = value[2]            citiao_qty = value[3].replace(u'词???条:','').replace(u'个','')            creator = value[4].replace(u'创建者:','')            size = value[5].replace(u'大???小:','')            update_tm = value[6].replace(u'更???新:','')            version = value[7].replace(u'版???本:','')            desc = value[8].replace('\n','')            if desc <> '':                print desc                out = '|'.join((type, name, popularity,url,citiao_qty,creator,size,update_tm,version,desc))                print out            elif desc == '' or desc == '\n':                out = '|'.join((type, name, popularity,url,citiao_qty,creator,size,update_tm,version,''))            out = out.replace(u'词???条:','').replace(u'个','').replace(u'创建者:','').replace(u'大???小:','').replace(u'更???新:','').replace(u'版???本:','')            if u'官方推荐' in name:                f_out.write(u'官方推荐' + '|'+ out +'\n')            else:                f_out.write(u'非推荐' + '|' + out +'\n' )

生成文件范例如下:

官方推荐|娱乐休闲|韩国国民CP夫妇大全【官方推荐】|753|http://download.pinyin.sogou.com/dict/download_cell.php?id=51539&name=%E9%9F%A9%E5%9B%BD%E5%9B%BD%E6%B0%91CP%E5%A4%AB%E5%A6%87%E5%A4%A7%E5%85%A8%E3%80%90%E5%AE%98%E6%96%B9%E6%8E%A8%E8%8D%90%E3%80%91&f=detail|146|pinyin|14364|2015-05-05 18:56:18|第1版本|韩国国民CP夫妇大全,韩国和中国最火的CP夫妇!非推荐|娱乐休闲|杰尼斯事务所|752|http://download.pinyin.sogou.com/dict/download_cell.php?id=31261&name=%E6%9D%B0%E5%B0%BC%E6%96%AF%E4%BA%8B%E5%8A%A1%E6%89%80&f=detail|234|745062548|17580|2012-06-09 16:29:51|第1版本|J家艺人名字PS:1.全汉字的名字(中日交杂的没有)2.除日文汉字外,其他汉字都是简体字3.Jr.及期间限定组合艺人的名字也有,但只是尽我所知

第二步,根据下载链接,下载词库。(只下载官方推荐词库,其他词库可以按照自己的需求调整代码下载)

#encoding=utf-8import sysdefaultencoding = 'utf-8'if sys.getdefaultencoding() != defaultencoding:    reload(sys)    sys.setdefaultencoding(defaultencoding)from codecs import openimport urlliburl_list_table = 'C:\\Users\\ijiao\\PycharmProjects\\fatedate\\jinqiao\\sogouciku\\sougouciku_list.txt'f1= open(url_list_table,'r','utf-8','ignore')for line in f1:    value = line.split('|')    if value[0] == u'官方推荐': #修改此处条件,下载所需词库        url = value[4].replace('"','')        print url        name = value[2]        print name        url_download_local = 'C:\\Users\\ijiao\\PycharmProjects\\fatedate\\jinqiao\\sogouciku\\sougoucihu_1\\'        url_total = url_download_local + name + '.scel'        print "downloading with urllib"        urllib.urlretrieve(url, url_total)

得到.scel格式的文件。

第三步:将搜狗格式的文件转换为txt格式。(网上大牛分享的代码,直接拿来用)

#!/usr/bin/python#encoding=utf-8import structimport reimport sysimport binasciiimport pdb# 搜狗的scel词库就是保存的文本的unicode编码,每两个字节一个字符(中文汉字或者英文字母)# 找出其每部分的偏移位置即可# 主要两部分# 1.全局拼音表,貌似是所有的拼音组合,字典序#       格式为(index,len,pinyin)的列表#       index: 两个字节的整数 代表这个拼音的索引#       len: 两个字节的整数 拼音的字节长度#       pinyin: 当前的拼音,每个字符两个字节,总长len## 2.汉语词组表#       格式为(same,py_table_len,py_table,{word_len,word,ext_len,ext})的一个列表#       same: 两个字节 整数 同音词数量#       py_table_len:  两个字节 整数#       py_table: 整数列表,每个整数两个字节,每个整数代表一个拼音的索引##       word_len:两个字节 整数 代表中文词组字节数长度#       word: 中文词组,每个中文汉字两个字节,总长度word_len#       ext_len: 两个字节 整数 代表扩展信息的长度,好像都是10#       ext: 扩展信息 前两个字节是一个整数(不知道是不是词频) 后八个字节全是0##      {word_len,word,ext_len,ext} 一共重复same次 同音词 相同拼音表# 拼音表偏移,startPy = 0x1540;# 汉语词组表偏移startChinese = 0x2628;# 全局拼音表GPy_Table = {}# 解析结果# 元组(词频,拼音,中文词组)的列表GTable = []def byte2str(data):    '''''将原始字节码转为字符串'''    i = 0;    length = len(data)    ret = u''    while i < length:        x = data[i] + data[i + 1]        t = unichr(struct.unpack('H', x)[0])        if t == u'\r':            ret += u'\n'        elif t != u' ':            ret += t        i += 2    return ret# 获取拼音表def getPyTable(data):    if data[0:4] != "\x9D\x01\x00\x00":        return None    data = data[4:]    pos = 0    length = len(data)    while pos < length:        index = struct.unpack('H', data[pos] + data[pos + 1])[0]        # print index,        pos += 2        l = struct.unpack('H', data[pos] + data[pos + 1])[0]        # print l,        pos += 2        py = byte2str(data[pos:pos + l])        # print py        GPy_Table[index] = py        pos += l# 获取一个词组的拼音def getWordPy(data):    pos = 0    length = len(data)    ret = u''    while pos < length:        index = struct.unpack('H', data[pos] + data[pos + 1])[0]        ret += GPy_Table[index]        pos += 2    return ret# 获取一个词组def getWord(data):    pos = 0    length = len(data)    ret = u''    while pos < length:        index = struct.unpack('H', data[pos] + data[pos + 1])[0]        ret += GPy_Table[index]        pos += 2    return ret# 读取中文表def getChinese(data):    # import pdb    # pdb.set_trace()    pos = 0    length = len(data)    while pos < length:        # 同音词数量        same = struct.unpack('H', data[pos] + data[pos + 1])[0]        # print '[same]:',same,        # 拼音索引表长度        pos += 2        py_table_len = struct.unpack('H', data[pos] + data[pos + 1])[0]        # 拼音索引表        pos += 2        py = getWordPy(data[pos: pos + py_table_len])        # 中文词组        pos += py_table_len        for i in xrange(same):            # 中文词组长度            c_len = struct.unpack('H', data[pos] + data[pos + 1])[0]            # 中文词组            pos += 2            word = byte2str(data[pos: pos + c_len])            # 扩展数据长度            pos += c_len            ext_len = struct.unpack('H', data[pos] + data[pos + 1])[0]            # 词频            pos += 2            count = struct.unpack('H', data[pos] + data[pos + 1])[0]            # 保存            GTable.append((count, py, word))            # 到下个词的偏移位置            pos += ext_lendef deal(file_name):    print '-' * 60    f = open(file_name, 'rb')    data = f.read()    f.close()    if data[0:12] != "\x40\x15\x00\x00\x44\x43\x53\x01\x01\x00\x00\x00":        print "确认你选择的是搜狗(.scel)词库?"        pass        # sys.exit(0)    # pdb.set_trace()    global ciku_name, ciku_type, ciku_desc,ciku_sample    # print ciku_name    ciku_name = byte2str(data[0x130:0x338]).replace('\n','').strip().replace('\r','').replace('\r\n','')  # .encode('GB18030')    ciku_type = byte2str(data[0x338:0x540]).replace('\n','').strip().replace('\r','').replace('\r\n','')  # .encode('GB18030')    ciku_desc = byte2str(data[0x540:0xd40]).replace('\n','').strip().replace('\r','').replace('\r\n','')  # .encode('GB18030')    ciku_sample = byte2str(data[0xd40:startPy]).replace('\n','').strip().replace('\r','').replace('\r\n','')  # .encode('GB18030')    print "词库名:", ciku_name  # .encode('GB18030')    print "词库类型:", ciku_type # .encode('GB18030')    print "描述信息:", ciku_desc  # .encode('GB18030')    print "词库示例:", ciku_sample  # .encode('GB18030')    getPyTable(data[startPy:startChinese])    getChinese(data[startChinese:])if __name__ == '__main__':    # 将要转换的词库添加在这里就可以了    import os    file_location = 'C:\\Users\\ijiao\\PycharmProjects\\fatedate\\jinqiao\\sogouciku\\sougoucihu_1'    for root,dirs,files in os.walk(file_location):        print files        for name in files:            locationname = file_location + '\\' + name            try:                deal(locationname)            except:                pass    # 保存结果    f = open('sougou.txt', 'w')    for count, py, word in GTable:        # GTable保存着结果,是一个列表,每个元素是一个元组(词频,拼音,中文词组),有需要的话可以保存成自己需要个格式        # 我没排序,所以结果是按照上面输入文件的顺序        data = unicode(ciku_name+ '|' + ciku_type + '|' + ciku_desc + '|' + ciku_sample+ '|'+'{%(count)s}' % {'count': count} + '|'+ py + '|' + word).encode('utf-8').replace('[\x00]','')        # data = re.sub('[\x00]', '', data)        f.write(data+'\n')  # 最终保存文件的编码,可以自给改        # f.write('\n')        # break    f.close()

完成!

0 0
原创粉丝点击