python封装成库函数 python中封装函数( 二 )


return True
else:
return False
def B2Q(uchar):
"""半角转全角"""
inside_code=ord(uchar)
if inside_code0x0020 or inside_code0x7e: #不是半角字符就返回原来的字符
return uchar
if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
inside_code=0x3000
else:
inside_code+=0xfee0
return unichr(inside_code)
def Q2B(uchar):
"""全角转半角"""
inside_code=ord(uchar)
if inside_code==0x3000:
inside_code=0x0020
else:
inside_code-=0xfee0
if inside_code0x0020 or inside_code0x7e: #转完之后不是半角字符返回原来的字符
return uchar
return unichr(inside_code)
def stringQ2B(ustring):
"""把字符串全角转半角"""
return "".join([Q2B(uchar) for uchar in ustring])
def uniform(ustring):
"""格式化字符串,完成全角转半角,大写转小写的工作"""
return stringQ2B(ustring).lower()
def string2List(ustring):
"""将ustring按照中文,字母,数字分开"""
retList=[]
utmp=[]
for uchar in ustring:
if is_other(uchar):
if len(utmp)==0:
continue
else:
retList.append("".join(utmp))
utmp=[]
else:
utmp.append(uchar)
if len(utmp)!=0:
retList.append("".join(utmp))
return retList
如何用Python封装C语言的字符串处理函数在C语言中,字符串处理是每天都要面对的问题 。我们都知道C语言中其实并没有一种原生的字符串类型,‘字符串’在C语言里只是一种特殊的以''结尾的字符数组 。因此 , 如何将C语言与更高层次的Python语言在‘字符串’处理这个问题上对接是一个有难度的问题 。所幸有swig这种强大的工具 。
如何封装一个函数,它修改参数字符串的内容
假如有这样一个C语言的函数,
!-- lang: cpp --
void FillZero(char* pc,size_t * piLen)
{
size_t i=0;
while(i++*piLen/2 )
*pc++ = '0';
*pc = 0;
*piLen = i+1;
}
这个函数的功能是把字符串变成n个0 。不过我们更关注函数的形式 。这样的函数,表面上看char* pc是函数的参数,可是实际上它才是函数的返回值和执行的结果 。piLen这个参数既是pc的最大长度,也是新的字符串的长度 。我们直接用python封装,看看运行结果 。
Type "help", "copyright", "credits" or "license" for more information.
import cchar
s='123456'
cchar.FillZero(s,6)
Traceback (most recent call last):
File "stdin", line 1, in module
TypeError: in method 'FillZero', argument 2 of type 'size_t *'
结果差强人意,不是我们想要得到的结果 。函数的第二个参数为size_t* 我们很难用python来表示,而且python中也不存在既是输入,也是输出的参数 。
swig有一个标准库,其中有一个cstring.i文件就是用来解决C语言字符串类型的问题 。
我们在.i文件中加入这样几行
!-- lang: cpp --
%include "cstring.i"
%cstring_output_withsize(char* pc,size_t* pi)
void FillZero(char* pc, size_t* pi);
然后运行看结果
Type "help", "copyright", "credits" or "license" for more information.
import cchar
cchar.FillZero(10)
'00000\x00'
s=cchar.FillZero(10)
print s
00000
我们看函数的变化 。首先在python里,FillZero变成了只有一个参数的函数 。然后函数的返回值变成了一个字符串 。其实cstring_output_size其实是一个宏,通过这个宏的定义改变了函数的形式,直接在Python中得到我们想要的结果 。
其实类似cstring_output_size的宏还有好几个,我列举一下:
cstring_output_allocate(char *s,free($1));
第一个参数是指向字符串地址的指针,第二个参数为释放空间的方法 。

推荐阅读