删除 dbf file/lib 中的空格

Remove spaces in dbf file/lib

我需要使用 python dbf 库过滤 dbf 文件。我在 dbf lib 上用一些方法做了一个 class,所以我有一个过滤记录的方法 search

def search(self, field_name: str, value: object) -> List:
    self._open_for_read()
    index = self._table.create_index(lambda rec: getattr(rec, field_name))
    records = index.search(match=(value,))
    return records

问题是,要么是 dbf 库添加了空白 space,要么是我的 dbf 文件包含我看不到的空白 space。

因此,要查询包含 Mattress 的名为 desceng 的字段,我需要添加空白 spaces。

 records = hifis.search('desceng',  'Mattress                                                                        ')

空白的数量 space 似乎取决于字段。

有没有办法删除空白的 spaces,所以我可以简单地用 'Mattress' 而不是 'Mattress ' 查询?

谢谢!

您可以做几件事:

  • trim 创建索引时的尾随空格:

    index = self._table.create_index(lambda rec: (getattr(rec, field_name) or '').strip())

  • 在打开数据库时使用 Char class,因为它会自动 trims 尾随空格:

    self._table = dbf.Table(..., default_data_types={'C':dbf.Char}