您的位置:首页 > 其它

访问子字符串

2015-10-22 10:46 344 查看
切片是个好方法,但是它一次只能取得一个字段;如果还考虑字段的长度,struct.unpack可能更适合。
import struct

def fields(baseformat, theline, lastfield=False):
    # theline超出的长度也由这个base-format确定
    # (通过struct.calcsize计算确切的长度)
    numremain = len(theline) - struct.calcsize(baseformat)
    # 用合适的s或x字段完成格式,然后unpack
    format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x")
    return struct.unpack(format, theline)  

利用缓存的方法:
import struct

def fields(baseformat, theline, lastfield=False, _cache={}):
# 生成键并尝试获得缓存的格式字符串
key = baseformat, len(theline), lastfield
format = _cache.get(key)
if format is None:
# 没有缓存的格式字符串,创建并缓存之
numremain = len(theline) - struct.calcsize(baseformat)
_cache[key] = format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x")
return struct.unpack(format, theline)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: