java - 如何获取搜狗输入法的词库
PHPz
PHPz 2017-04-17 11:22:37
[Java讨论组]

用Lucene做了个文档检索系统,对于分词维护一套字典,现在想把例如搜狗输入法的热门词库同步到我的字典中,但是发现搜狗输入法好像没有对外的API,请问有什么实现方式,别的中文输入法能实现也可以。

PHPz
PHPz

学习是最好的投资!

全部回复(1)
黄舟

我忘记这代码是从哪儿来的了,大概是从这个改的吧:http://yongsun.me/2010/07/%E5%AF%BC%E5%85%A5sogou%E8%BE%93%E5%85%A5%E6%B3%95%E7%9A%84%E7%BB%86%E8%83%9E%E8%AF%8D%E5%BA%93/

importer.py

#!/usr/bin/python2
import struct
import os, sys

def read_utf16_str (f, offset=-1, len=2):
    if offset >= 0:
        f.seek(offset)
    str = f.read(len)
    return str.decode('UTF-16LE')

def read_uint16 (f):
    return struct.unpack ('<H', f.read(2))[0]

def get_word_from_sogou_cell_dict (fname):
    f = open (fname, 'rb')
    file_size = os.path.getsize (fname)

    hz_offset = 0
    mask = struct.unpack ('B', f.read(128)[4])[0]
    if mask == 0x44:
        hz_offset = 0x2628
    elif mask == 0x45:
        hz_offset = 0x26c4
    else:
        sys.exit(1)

    title   = read_utf16_str (f, 0x130, 0x338  - 0x130)
    type    = read_utf16_str (f, 0x338, 0x540  - 0x338)
    desc    = read_utf16_str (f, 0x540, 0xd40  - 0x540)
    samples = read_utf16_str (f, 0xd40, 0x1540 - 0xd40)

    py_map = {}
    f.seek(0x1540+4)

    while 1:
        py_code = read_uint16 (f)
        py_len  = read_uint16 (f)
        py_str  = read_utf16_str (f, -1, py_len)

        if py_code not in py_map:
            py_map[py_code] = py_str

        if py_str == 'zuo':
            break

    f.seek(hz_offset)
    while f.tell() != file_size:
        word_count   = read_uint16 (f)
        pinyin_count = read_uint16 (f) / 2

        py_set = []
        for i in range(pinyin_count):
            py_id = read_uint16(f)
            py_set.append(py_map[py_id])
        py_str = "'".join (py_set)

        for i in range(word_count):
            word_len = read_uint16(f)
            word_str = read_utf16_str (f, -1, word_len)
            f.read(12) 
            yield py_str, word_str

    f.close()

def showtxt (records):
    for (pystr, utf8str) in records:
        #print len(utf8str), utf8str
        print utf8str.encode('utf8')

def main ():
    if len (sys.argv) != 2:
        print "Please specify the Sogou PinYin Cell dict file!"
        exit (1)

    generator = get_word_from_sogou_cell_dict (sys.argv[1])
    showtxt(generator)

if __name__ == "__main__":
    main()

然后到 http://pinyin.sogou.com/dict/ 下载搜狗细胞词库。运行 ./importer.py 文件名

运行后会向标准输出输出 *.scel 文件里的所有词,每行一个。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号