使用Python实现GBK转unicode码查询表

接触python有一段时间了,但没有专门学习基础知识,写代码时总是到网上找资料。不过,相信经过练习可以慢慢积累。本文拿以前写的小程序练手。参见文章《GBK转unicode码查询表的改进》。

涉及python知识:
1、先初始化好一个65535大小的列表。开始我想直接定义buffer = [65535],但这和C的不同,所以使用append方式初始化0——因为这样才生成65535个列表。
2、由于GBK编码索引不连续,所以使用buffer[x2] = x1这种形式赋值。开始使用insert方式,但结果不正确。 源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/python
# encoding: utf-8

import os
import datetime
import time

SRC = "gbkuni30.txt"
DST = "gbkuni30_gen1.h"
ARRAY = "gbkuni30"

buffer = [] # 空列表
max_num = 0

# 初始化好buffer,一共65535
for i in range(0, 65535):
buffer.append(0x0)

try:
f = open(SRC, 'r')
while True:
l = f.readline()
if l == '':
break;
s = l.strip().split(':') #以:分割,生成不同个数的列表
if len(s) == 2:
x1 = int(s[0], 16) # 字符串转换为十六进制
x2 = int(s[1], 16)
buffer[x2] = x1 # 针对索引赋值
if x2 > max_num:
max_num = x2
#print("%04x %04x" % (x2, x1))
print("max num %d %x len: %d" % (max_num, max_num, len(buffer)))
except:
raise
f = open(DST, "w")
test = "/**********************************************************************************/\n"
test += "/* GBK(GB18030) to UNICODE table, powered by Late Lee */\n"
test += "/* http://www.latelee.org */\n"
test += "/* %s */\n" % (datetime.datetime.now())
test += "/* The source file comes from: */\n"
test += "/* http://icu-project.org/repos/icu/data/trunk/charset/source/gb18030/gbkuni30.txt*/\n"
test += "/**********************************************************************************/\n"
test += "#ifndef __GBK2UNICODE__H\n"
test += "#define __GBK2UNICODE__H\n\n"
test += "static unsigned short %s[] = \n{\n" % (ARRAY)
f.write(test) # write text to file
####
cnt=0
for i in range(0x8140, max_num+1):
#print("%x -- 0x%x" % (i, buffer[i]))
ch = "0x%04x, " % (buffer[i])
f.write(ch)
cnt+=1;
if cnt % 10 == 0:
tmp = " // line num %d \n" % (cnt / 10 - 1)
f.write(tmp)
########
test= "\n"
test+= "};\n\n"
test+= "#endif //__GBK2UNICODE__H\n"

f.write(test) # write text to file
f.close()

生成的头文件与使用C版本实现的一致。

李迟 2015.1.15 周日 中午