搜狗词库scel格式转为txt格式(python3版本)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gsch_12/article/details/82083474

1、想用搜狗的词库来辅助jieba分词,需要把词库从scel转成txt格式。
在网上找到了大神的python2版本,https://blog.csdn.net/zhangzhenhu/article/details/7014271
但在python3里有许多不兼容更多地方,于是按照这个教程把有问题的地方改了过来。
教程:https://blog.csdn.net/sunlilan/article/details/78761659#commentBox
教程有一个地方没写清楚,有一个地方漏写了。于是完善一下修改教程,并附带源码。


最近需要词库来优化分词效果,找到了有大神写好的能将搜狗词库scel转成txt的python脚本。
http://blog.csdn.net/zhangzhenhu/article/details/7014271
实际运行时因为python版本不同转换不能成功,最后终于可行。

bytes与16进制字符串

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)词库?")
    sys.exit(0)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

程序刚开始运行由于if判断语句中的两者不相等就退出了

两者确实是不相等的,但用notepad hex editor查看前12个字符确实是
\x40\x15\x00\x00\x44\x43\x53\x01\x01\x00\x00\x00

这里写图片描述

以二进制模式来读取文件,data=f.read() 是bytes对象。

>>> type(data)
<class 'bytes'>
>>> data[0:12]
b'@\x15\x00\x00DCS\x01\x01\x00\x00\x00'
  
  
  • 1
  • 2
  • 3
  • 4

一个bytes对象b,b[0]的类型是int,而b[0:1]的类型是长度为1的bytes对象。
bytes对象的表示:b’…’
list(b)可以把一个bytes对象转换为a list of integer

需要了解的两个方法:
bytes.fromhex(string):This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.

hex():Return a string object containing two hexadecimal digits for each byte in the instance.

>>> list(data[0:12])
[64, 21, 0, 0, 68, 67, 83, 1, 1, 0, 0, 0]

>>> data[0:12].hex()
'401500004443530101000000'
>>> bytes.fromhex('401500004443530101000000')
b'@\x15\x00\x00DCS\x01\x01\x00\x00\x00'
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

通过hex()方法转成的16进制字符串虽然确实是我们要的,但是它缺少\x,if判断语句中的两者依然不相等

bytes转string不通,考虑string转bytes,使用如下语句即可

bytes(map(ord,"\x40\x15\x00\x00\x44\x43\x53\x01\x01\x00\x00\x00"))
  
  
  • 1

unichr

Traceback (most recent call last):
  File "F:/sogou/scel_to_txt.py", line 178, in <module>
    deal(f)
  File "F:/sogou/scel_to_txt.py", line 162, in deal
    print ("词库名:", byte2str(data[0x130:0x338]))  # .encode('GB18030')
  File "F:/sogou/scel_to_txt.py", line 56, in byte2str
    t = unichr(struct.unpack('H', x)[0])
NameError: name 'unichr' is not defined
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

https://stackoverflow.com/questions/2352018/cant-use-unichr-in-python-3-1
把unichr换为chr即可。

In Python 3,
there’s no difference between unicode and normal strings anymore.
Only between unicode strings and binary data.
So the developers finally removed the unichr function in favor of a common chr which now does what the old unichr did.
python3.x中所有的string都是unicode string,因此开发者移除了unichr

chr()函数用一个范围在range(256)内的(就是0~255)整数作参数,返回一个对应的字符
ord()函数是chr()函数的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值

>>> chr(65)
'A'
>>> ord('a')
97
  
  
  • 1
  • 2
  • 3
  • 4

struct.unpack

Traceback (most recent call last):
  File "F:/sogou/scel_to_txt.py", line 178, in <module>
    deal(f)
  File "F:/sogou/scel_to_txt.py", line 162, in deal
    print ("词库名:", byte2str(data[0x130:0x338]))  # .encode('GB18030')
  File "F:/sogou/scel_to_txt.py", line 56, in byte2str
    t = chr(struct.unpack('H', x)[0])
TypeError: a bytes-like object is required, not 'int'
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
def byte2str(data):
    '''''将原始字节码转为字符串'''
    i = 0;
    length = len(data)
    ret = u''
    while i < length:
        x = data[i]+data[i+1]
        t = chr(struct.unpack('H', x)[0])
        if t == u'\r':
            ret += u'\n'
        elif t != u' ':
            ret += t
        i += 2
    return ret
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

上面提到过bytes对象b,b[0]是int,b[0:2]才是bytes对象。
把所有data[i]+data[i+1]的地方修改为data[i:i+2]
**原教程补充:要全局搜data[pos]+data[pos+1]改成data[pos:pos +2]**

>>> data[0:2]
b'\xa1\x8b'
>>> struct.unpack('H',data[0:2])
(35745,)
>>> chr(struct.unpack('H',data[0:2])[0])
'计'
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

pack(fmt, v1, v2, …)
按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)

unpack(fmt, string)
按照给定的格式(fmt)解析字节流string,返回解析出来的tuple

#字节串转整数:
#转为short型整数: 
struct.unpack('hh', bytes(b'\x01\x00\x00\x00'))
(1, 0)
#转义为long型整数: 
struct.unpack('L', bytes(b'\x01\x00\x00\x00'))
(1,)


#整数转字节串:
#转为两个字节: 
struct.pack('HH', 1,2)
b'\x01\x00\x02\x00'
#转为四个字节: 
struct.pack('LL', 1,2)
b'\x01\x00\x00\x00\x02\x00\x00\x00'
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

格式,类型,python类型
h,short,integer,2
H,unsigned short,integer,2
i,int,integer ,4
I,unsigned int,integer,4
l,long,integer,4
L,unsigned long,integer,4
q,long long,integer,8
Q,unsigned long long,integer,8
f,float,float,4
d,double,float,8
s,char[],string

每个格式前可以有一个数字,表示个数

xrange

Traceback (most recent call last):
  File "F:/sogou/scel_to_txt.py", line 178, in <module>
    deal(f)
  File "F:/sogou/scel_to_txt.py", line 168, in deal
    getChinese(data[startChinese:])
  File "F:/sogou/scel_to_txt.py", line 131, in getChinese
    for i in xrange(same):
NameError: name 'xrange' is not defined
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

最后把xrange改为range
原教程补充:
出现错误:name ‘unicode’ is not defined”
原因:python3就没有unicode的方法,是默认utf-8的
修改如下:
原句:

f.write( unicode('{%(count)s}' %{'count':count}+py+' '+ word).encode('GB18030') )

改成

f.write((('{%(count)s}' % {'count': count} + py + ' ' + word)))  

程序运行成功

这里写图片描述

完整代码分享:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import struct
import sys
import binascii
import 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:i+2]
        t =  chr(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] != bytes(map(ord,"\x9D\x01\x00\x00")):
        return None
    data = data[4:]
    pos = 0
    length = len(data)
    while pos < length:
        index = struct.unpack('H', data[pos:pos +2])[0]
        # print index,
        pos += 2
        l = struct.unpack('H', data[pos:pos + 2])[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:pos + 2])[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:pos +2])[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:pos + 2])[0]
        # print '[same]:',same,

        # 拼音索引表长度
        pos += 2
        py_table_len = struct.unpack('H', data[pos:pos + 2])[0]
        # 拼音索引表
        pos += 2
        py = getWordPy(data[pos: pos + py_table_len])

        # 中文词组
        pos += py_table_len
        for i in range(same):
            # 中文词组长度
            c_len = struct.unpack('H', data[pos:pos +2])[0]
            # 中文词组
            pos += 2
            word = byte2str(data[pos: pos + c_len])
            # 扩展数据长度
            pos += c_len
            ext_len = struct.unpack('H', data[pos:pos +2])[0]
            # 词频
            pos += 2
            count = struct.unpack('H', data[pos:pos +2])[0]

            # 保存
            GTable.append((count, py, word))

            # 到下个词的偏移位置
            pos += ext_len


def deal(file_name):
    print
    '-' * 60
    f = open(file_name, 'rb')
    data = f.read()
    f.close()

    if data[0:12] != bytes(map(ord,"\x40\x15\x00\x00\x44\x43\x53\x01\x01\x00\x00\x00")):
        print
        "确认你选择的是搜狗(.scel)词库?"
        sys.exit(0)
    # pdb.set_trace()

    print
    "词库名:", byte2str(data[0x130:0x338])  # .encode('GB18030')
    print
    "词库类型:", byte2str(data[0x338:0x540])  # .encode('GB18030')
    print
    "描述信息:", byte2str(data[0x540:0xd40])  # .encode('GB18030')
    print
    "词库示例:", byte2str(data[0xd40:startPy])  # .encode('GB18030')

    getPyTable(data[startPy:startChinese])
    getChinese(data[startChinese:])


if __name__ == '__main__':

    # 将要转换的词库添加在这里就可以了
    o = ['gq.scel']

    for f in o:
        deal(f)

    # 保存结果
    f = open('sougou.txt', 'w')
    for count, py, word in GTable:
        # GTable保存着结果,是一个列表,每个元素是一个元组(词频,拼音,中文词组),有需要的话可以保存成自己需要个格式
        # 我没排序,所以结果是按照上面输入文件的顺序
        f.write((('{%(count)s}' % {'count': count} + py + ' ' + word)))  # 最终保存文件的编码,可以自给改
        f.write('\n')
    f.close()

猜你喜欢

转载自blog.csdn.net/gsch_12/article/details/82083474
今日推荐