自制常用功能接口(Python)

Last Updated: 2023-10-04 07:31:41 Wednesday

-- TOC --

写过的python代码不少,自己积累了一些比较基础和常用的接口,在这里存放一些。

shex和sbin

shex和sbin,s代表single和simple,他们python自带的hex和bin的限制扩展:

from functools import partial


def shex(ch, *, prefix=True, upper=True):
    """Return the full hex representation of ch w/o 0x prefix.
    ch is 0 -- 255 (Small range) in int type, since python has no char type.
    The hex function in stdlib would omit the leading zero, shex would not.
    """
    if ch < 0 or ch > 255:
        raise ValueError('ch should be 0 -- 255.')
    rt = hex(ch)[2:].upper() if upper else hex(ch)[2:]
    return '0x'+rt.rjust(2,'0') if prefix else rt.rjust(2,'0')


shex_pu = partial(shex)
shex_u = partial(shex, prefix=False)
shex_pl = partial(shex, upper=False)
shex_l = partial(shex, prefix=False, upper=False)


def sbin(ch, *, prefix=True):
    """Return the full bin representation of ch w/o 0b prefix.
    ch is 0 -- 255 (Small range) in int type, since python has no char type.
    The bin function in stdlib would omit the leading zero, sbin would not.
    """
    if ch < 0 or ch > 255:
        raise ValueError('ch should be 0 -- 255.')
    rt = bin(ch)[2:].rjust(8,'0')
    return '0b'+rt if prefix else rt


sbin_0b = partial(sbin)
sbin_01 = partial(sbin, prefix=False)

normalize keys of dict object

所谓normalize keys of dict object,就是将一个dict对象的所有的key,统一做大小写转换,以及strip,以方便后续代码处理。

比如用户给的json格式数据,在Python内部用dict对象表示,此时做normalization,就可以方便后续代码处理用户输入的数据。也不需要去考虑字符串是否需要strip,大小写不对怎么版等细节问题...

def chDictKey(odict, keycase='lower', recur=True):
    """Return a new dict with changed keys (also stripped) in keycase.
    keycase: lower(default), upper.
    The recursive effect is only applied to dict elements in dict object.
    """
    if not isinstance(odict, dict):
        return odict
    ndict = dict()
    for k,v in odict.items():
        _k = eval('k.'+keycase+'().strip()')
        ndict[_k] = chDictKey(v, keycase, 1) if recur else v
    return ndict

以上递归实现,keycase的取值只能是lower或upper,这个值要通过拼接字符串,在eval里面执行。

也许这个函数的名称应该改一改,体现出normalize的意思,比如norm_dick_keys。

对字符串实现最右数字部分+1

一个小函数,可以实现对含有字符的字符串的最有部分的数字加1,在操作SN(序列号)这样的数据时,还有点用。

_re_incr14Str = re.compile(r'(\d+)([^\d]*$)')


def incr14Str(string):
    """Increase one (+1) for the LAST number partition of string.
    If in case abcd999ko, return abcd000ko after +1.
    The length of string keeps the same.
    """
    rt = _re_incr14Str.search(string)
    if rt:
        pos_left = rt.span()[0]
        num = int(rt.groups()[0])
        numStr = ''
        for i in range(len(rt.groups()[0])-len(str(num+1))):
            numStr += '0'
        else:
            numStr += str(num+1)
        return (string[:pos_left]
                + numStr[len(numStr)-len(rt.groups()[0]):]
                + rt.groups()[1])
    else:
        raise ValueError('No suitable number partition found.')

思路不复杂,先通过正则表达式找出最右边的数字部分,加1后,再拼接会原字符串中。如果遇到999这样的情况,+1后会变成000,函数优先确保字符串的长度不变。

含中文字符串的对齐

当字符串中有中文的时候,在输出显示的时候,对齐是一个技术活,本文收录两个自己以前写的接口函数,可以应在这样的场景下。

def chlen(string):
    """Return the ascii space length of the string.
    In case there are Chinese symbols in string, which occupys 2 ascii spaces
    each. I assume all the length of unicode of non-ascii char is 2.
    """
    if string.isascii():
        return len(string)
    length = 0
    for it in list(string):
        length = length+1 if it.isascii() else length+2
    return length

chlen返回一个字符串的ascii长度,每个中文字符的长度为2

def chstr(string, length, align):
    """Return a new string extended by space (ascii) and aligned.
    length should larger than real ascii length of string (chlen),
    align is either 'left', 'middle' or 'right',
    Chinese symbol in string is the purpose and supported.
    """
    real_len = chlen(string)
    if real_len > length:
        raise ValueError('length is too small.')
    if real_len == length:
        return string
    needed = length - real_len
    if align == 'left':
        return string + ' '*needed
    if align == 'right':
        return ' '*needed + string
    # middle
    half_space = ' ' * int(needed/2)
    rt = half_space + string + half_space
    return rt if needed%2==0 else rt+' '

chstr接口用来输出对齐的时候,它会调用chlen接口。

本文链接:https://cs.pynote.net/sf/python/202206081/

-- EOF --

-- MORE --