跳转到主要内容

用于快速随机访问的二分搜索二进制文件

项目描述

binarysearchfile

用于快速随机访问的二分搜索排序二进制文件

使用方法

定义并使用自己的二分搜索文件

from binarysearchfile import BinarySearchFile

class MyBinarySearchFile(BinarySearchFile):
    magic = b'\xfe\xff\x01\x01'  # magic string, you can change 2nd and 4th byte
    headerstart = b'MyBinarySearchFile'  # name of the file format
    record = (50, 50)  # record structure, here two ints, first field can be searched binarily

bsf = MyBinarySearchFile('mybinarysearchfile')
data = [(10, 42), (4, 10), (5, 5)]
bsf.write(data)  # write sorted data
print(len(bsf))  # number of records
print(bsf.search(10))  # get index
print(bsf.get(10))  # get record
print(bsf)  # print file information

#Output:
#3
#2
#(10, 42)
#MyBinarySearchFile
#     fname: mybinarysearchfile
#   records: 3
#      size: 40.00 Byte
#   recsize: 2 Byte  (1, 1)

上面的示例定义了由两个整数组成的记录。记录中的第一个元素("键")可以二分搜索。目前,以下类型可以开箱即用

0: binary adding whitepace
10: ascii adding whitespace
20: utf-8 adding whitespace
50: int
51: signedint

可以由原始类读取文件

bsf = BinarySearchFile('mybinarysearchfile')
print(bsf.get(10))

#Output:
#(10, 42)

文件格式在模块的文档字符串中指定。

定义自己的数据类型

使用以下方法使用DTypeDef类定义额外的自定义类型。它的init方法接受namelenencodedecode参数。其中len,对象的字节长度,通常是对象的函数,但对于固定长度可以是整数。仅将自定义类型与键大于99注册。

from binarysearchfile import BinarySearchFile, DTypeDef

class MyBinarySearchFile(BinarySearchFile):
    DTYPE = BinarySearchFile.DTYPE.copy()
    DTYPE[100] = DTypeDef(
        'fixedlenint', 5,
        encode=lambda v, s: v.to_bytes(s),
        decode=lambda v: int.from_bytes(v)
        )
    # definitions of other class properties follow

使用二进制顺序文件

我们提供了一个BinarySequentialFile类,它使用相同的文件布局,可以用于顺序读取和写入。

from binarysearchfile import BinarySequentialFile
with BinarySequentialFile('mybinarysearchfile') as bseqf:
    print(bseqf[2])

#Output:
#(10, 42)

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

binarysearchfile-0.2.0.tar.gz (7.1 kB 查看哈希值)

上传时间

构建分发

binarysearchfile-0.2.0-py3-none-any.whl (7.2 kB 查看哈希值)

上传时间 Python 3

由以下组织支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面