unicode转gbk python_使用python实现GBK转unicode码查询表
接觸python有一段時間了,但沒有專門學習基礎知識,寫代碼時總是到網上找資料。不過,相信經過練習可以慢慢積累。本文拿以前寫的小程序練手。參見文章《GBK轉unicode碼查詢表的改進》。
涉及python知識:
1、先初始化好一個65535大小的列表。開始我想直接定義buffer = [65535],但這和C的不同,所以使用append方式初始化0——因為這樣才生成65535個列表。
2、由于GBK編碼索引不連續,所以使用buffer[x2] = x1這種形式賦值。開始使用insert方式,但結果不正確。
源碼如下:
#!/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 周日 中午
總結
以上是生活随笔為你收集整理的unicode转gbk python_使用python实现GBK转unicode码查询表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】Linux下定时删除指定目下n天前
- 下一篇: GPS GGA格式