跳转到主要内容

用于流式读写表格数据(csv/xls/json等)的统一接口

项目描述

tabulator-py

Travis Coveralls PyPi Github Gitter

一个用于读取和写入表格数据的库(csv/xls/json等)。

[重要通知] 我们已发布Frictionless Framework。此框架是tabulator的逻辑延续,扩展成为一个完整的数据解决方案。这次变更不会破坏现有的软件,因此无需采取任何操作。请阅读从tabulator到Frictionless Framework的迁移指南

  • 我们仍然在这个仓库中修复tabulator@1.x的bug,并且它仍然可以在PyPi上找到,和之前一样。
  • 请注意,我们目前正在开发的frictionless@3.x版本的API并不稳定。
  • 我们将在2020年底发布frictionless@4.x版本,作为第一个SemVer/stable版本。

功能

  • 支持大多数常见的表格格式:CSV、XLS、ODS、JSON、Google Sheets、SQL以及其他。请参阅以下完整列表
  • 支持本地和远程数据:支持HTTP、FTP和S3。
  • 内存使用低:只保留当前行在内存中,因此可以处理大型数据集。
  • 支持压缩文件:使用ZIP或GZIP算法。
  • 可扩展:您可以添加对自定义文件格式和加载器的支持(例如FTP)。

内容

入门

安装

$ pip install tabulator

在CLI上运行

Tabulator附带了名为tabulator的简单CLI,用于读取表格数据。例如

$ tabulator https://github.com/frictionlessdata/tabulator-py/raw/4c1b3943ac98be87b551d87a777d0f7ca4904701/data/table.csv.gz
id,name
1,english
2,中国人

运行tabulator --help可以查看所有支持的选项。

在Python上运行

from tabulator import Stream

with Stream('data.csv', headers=1) as stream:
    stream.headers # [header1, header2, ..]
    for row in stream:
        print(row)  # [value1, value2, ..]

其他示例可以在examples目录中找到。

文档

在以下部分,我们将演示这个库的一些使用示例。所有示例都在Python 3.6上测试过,但也应该在Python 3.3+上运行良好。

与流一起工作

Stream类代表一个表格流。它将文件路径作为source参数。例如

<scheme>://path/to/file.<format>

它使用此路径来确定文件格式(例如CSV或XLS)和方案(例如HTTP或postgresql)。它还支持从URL中提取格式,例如http://example.com?format=csv。如果需要,您也可以明确定义这些。

让我们试试。首先,我们创建一个Stream对象,传递CSV文件的路径。

import tabulator

stream = tabulator.Stream('data.csv')

此时,文件尚未被读取。让我们打开流,以便我们可以读取内容。

try:
    stream.open()
except tabulator.TabulatorException as e:
    pass  # Handle exception

这将打开底层数据流,读取一小部分以检测文件编码,并准备要读取的数据。我们在这里捕获tabulator.TabulatorException,以防出现错误。

现在我们可以读取文件内容了。要遍历每一行,我们执行以下操作

for row in stream.iter():
    print(row)  # [value1, value2, ...]

stream.iter()方法将返回作为值列表的每一行数据。如果您愿意,也可以调用stream.iter(keyed=True),它将返回一个以列名作为键的字典。无论哪种方式,此方法一次只保留一行在内存中。这意味着它可以处理大型文件而不会消耗太多内存。

如果您想读取整个文件,请使用stream.read()。它接受与stream.iter()相同的参数,但一次返回所有行。

stream.reset()
rows = stream.read()

请注意,我们在读取行之前调用了 stream.reset()。这是因为内部,tabulator 只保存对文件当前位置的指针。如果我们不重置这个指针,我们将从停止的地方开始读取。例如,如果我们再次运行 stream.read(),我们会得到一个空列表,因为内部文件指针位于文件末尾(因为我们已经全部读取了)。根据文件位置,可能需要再次下载文件以回滚(例如,当文件从网络加载时)。

完成后,使用以下方法关闭流

stream.close()

整个示例看起来像

import tabulator

stream = tabulator.Stream('data.csv')
try:
    stream.open()
except tabulator.TabulatorException as e:
    pass  # Handle exception

for row in stream.iter():
    print(row)  # [value1, value2, ...]

stream.reset()  # Rewind internal file pointer
rows = stream.read()

stream.close()

可以改写为使用 Python 的上下文管理器接口,如下所示

import tabulator

try:
    with tabulator.Stream('data.csv') as stream:
        for row in stream.iter():
            print(row)

        stream.reset()
        rows = stream.read()
except tabulator.TabulatorException as e:
    pass

这是首选方法,因为即使在过程中抛出了异常,Python 也会自动关闭流。

完整的 API 文档作为 docstrings 可在 Stream 源代码 中找到。

标题

默认情况下,tabulator 认为所有文件行都是值(即没有标题)。

with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.headers # None
  stream.read() # [['name', 'age'], ['Alex', 21]]

如果您有一个标题行,可以使用 headers 参数并指定其行号(从 1 开始)。

# Integer
with Stream([['name', 'age'], ['Alex', 21]], headers=1) as stream:
  stream.headers # ['name', 'age']
  stream.read() # [['Alex', 21]]

您还可以传递字符串列表来显式定义标题

with Stream([['Alex', 21]], headers=['name', 'age']) as stream:
  stream.headers # ['name', 'age']
  stream.read() # [['Alex', 21]]

Tabulator 还支持 xlsxlsx 格式的多行标题。

with Stream('data.xlsx', headers=[1, 3], fill_merged_cells=True) as stream:
  stream.headers # ['header from row 1-3']
  stream.read() # [['value1', 'value2', 'value3']]

编码

您可以通过 encoding 参数指定文件编码(例如 utf-8latin1)。

with Stream(source, encoding='latin1') as stream:
  stream.read()

如果此参数未设置,Tabulator 将尝试从数据中推断它。如果在加载文件时遇到 UnicodeDecodeError,请尝试将编码设置为 utf-8

压缩(仅限 Python3)

Tabulator 支持ZIP和GZIP压缩方法。默认情况下,它会从文件名推断。

with Stream('http://example.com/data.csv.zip') as stream:
  stream.read()

您也可以显式设置它

with Stream('data.csv.ext', compression='gz') as stream:
  stream.read()

选项

  • filename:zip文件中要处理的文件名(默认为第一个文件)

允许 HTML

如果 Stream 类检测到 HTML 内容,它会引发 tabulator.exceptions.FormatError。这有助于避免相对常见的错误,例如尝试在 HTML 页面中加载 CSV 文件,例如在 GitHub 上。

您可以使用 allow_html 选项禁用此行为

with Stream(source_with_html, allow_html=True) as stream:
  stream.read() # no exception on open

样本大小

为了检测文件的标题并运行其他检查,例如验证文件不包含 HTML,Tabulator 在 stream.open() 方法上读取行的一小部分。这些数据通过 stream.sample 属性可用。使用的行数可以通过 sample_size 参数定义(默认为 100)。

with Stream(two_rows_source, sample_size=1) as stream:
  stream.sample # only first row
  stream.read() # first and second rows

您可以通过将 sample_size 设置为零来禁用它。这样,在 stream.open() 上不会读取任何数据。

字节样本大小

Tabulator 需要读取文件的一部分以推断其编码。bytes_sample_size 参数控制用于此检测的多少字节(默认为 10000)。

source = 'data/special/latin1.csv'
with Stream(source) as stream:
    stream.encoding # 'iso8859-2'

您可以通过将 bytes_sample_size 设置为零来禁用它,在这种情况下,它将使用机器区域设置的默认编码。

忽略空标题

True 时,tabulator 将忽略具有空标题的列(默认为 False)。

# Default behaviour
source = 'text://header1,,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1) as stream:
    stream.headers # ['header1', '', 'header3']
    stream.read(keyed=True) # {'header1': 'value1', '': 'value2', 'header3': 'value3'}

# Ignoring columns with blank headers
source = 'text://header1,,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1, ignore_blank_headers=True) as stream:
    stream.headers # ['header1', 'header3']
    stream.read(keyed=True) # {'header1': 'value1', 'header3': 'value3'}

忽略列出/未列出标题

此选项类似于 ignore_blank_headers。它根据相应的列名称从数据中删除任意列

# Ignore listed headers (omit columns)
source = 'text://header1,header2,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1, ignore_listed_headers=['header2']) as stream:
    assert stream.headers == ['header1', 'header3']
    assert stream.read(keyed=True) == [
        {'header1': 'value1', 'header3': 'value3'},
    ]

# Ignore NOT listed headers (pick colums)
source = 'text://header1,header2,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1, ignore_not_listed_headers=['header2']) as stream:
    assert stream.headers == ['header2']
    assert stream.read(keyed=True) == [
        {'header2': 'value2'},
    ]

强制字符串

True 时,所有行的值都将转换为字符串(默认为 False)。None 值将转换为空字符串。

# Default behaviour
with Stream([['string', 1, datetime.datetime(2017, 12, 1, 17, 00)]]) as stream:
  stream.read() # [['string', 1, datetime.dateime(2017, 12, 1, 17, 00)]]

# Forcing rows' values as strings
with Stream([['string', 1]], force_strings=True) as stream:
  stream.read() # [['string', '1', '2017-12-01 17:00:00']]

强制解析

True 时,在解析格式错误的行时不要引发异常,而是简单地返回空行。否则,当一行无法解析时,tabulator 会引发 tabulator.exceptions.SourceError。默认为 False

# Default behaviour
with Stream([[1], 'bad', [3]]) as stream:
  stream.read() # raises tabulator.exceptions.SourceError

# With force_parse
with Stream([[1], 'bad', [3]], force_parse=True) as stream:
  stream.read() # [[1], [], [3]]

跳过行

跳过的行号和/或字符串列表。如果是字符串,所有以该字符串开头的行都将被跳过(例如 '#' 和 '//')。如果是空字符串,所有以空列开头的行都将被跳过。

source = [['John', 1], ['Alex', 2], ['#Sam', 3], ['Mike', 4], ['John', 5]]
with Stream(source, skip_rows=[1, 2, -1, '#']) as stream:
  stream.read() # [['Mike', 4]]

如果 headers 参数也设置为整数,则将使用第一个未被跳过的行作为标题。

source = [['#comment'], ['name', 'order'], ['John', 1], ['Alex', 2]]
with Stream(source, headers=1, skip_rows=['#']) as stream:
  stream.headers # [['name', 'order']]
  stream.read() # [['Jogn', 1], ['Alex', 2]]

解析后

可以过滤或转换解析后行的函数列表。这些函数接收包含行号、标题列表和行值列表的 extended_rows。然后它们处理行,并生成或丢弃修改后或未修改的行。

def skip_odd_rows(extended_rows):
    for row_number, headers, row in extended_rows:
        if not row_number % 2:
            yield (row_number, headers, row)

def multiply_by_two(extended_rows):
    for row_number, headers, row in extended_rows:
        doubled_row = list(map(lambda value: value * 2, row))
        yield (row_number, headers, doubled_row)

rows = [
  [1],
  [2],
  [3],
  [4],
]
with Stream(rows, post_parse=[skip_odd_rows, multiply_by_two]) as stream:
  stream.read() # [[4], [8]]

这些函数按顺序应用,作为一个简单的数据处理管道。在上面的示例中,multiply_by_two 只看到 skip_odd_rows 生成的行。

键和扩展行

stream.iter()stream.read() 方法接受 keyedextended 标志参数以修改返回行的格式。

默认情况下,每行都作为其单元格值的列表返回。

with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.read() # [['Alex', 21]]

使用 keyed=True,行以字典的形式返回,列名映射到行中的值。

with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.read(keyed=True) # [{'name': 'Alex', 'age': 21}]

使用 extended=True,行以一个包含 (row_number, headers, row) 的元组形式返回,其中 row_number 是当前行号(从 1 开始),headers 是包含标题名称的列表,而 row 是包含行值的列表。

with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.read(extended=True) # (1, ['name', 'age'], ['Alex', 21])

支持的方案

s3

它从 AWS S3 加载数据。对于私有文件,您应该提供 boto3 库支持的凭证,例如相应的环境变量。更多信息请参阅 配置 boto3

stream = Stream('s3://bucket/data.csv')

选项

  • s3_endpoint_url - 要使用的端点 URL。默认为 https://s3.amazonaws.com。对于复杂用例,例如在数据包上运行 goodtables,此选项可以作为环境变量 S3_ENDPOINT_URL 提供。

file

默认方案,本地文件系统中的文件。

stream = Stream('data.csv')

http/https/ftp/ftps

在 Python 2 中,由于底层库的限制,tabulator 不能流式传输远程数据源。整个数据源将被加载到内存中。在 Python 3 中没有这个问题,远程文件可以流式传输。

stream = Stream('https://example.com/data.csv')

选项

  • http_session - 一个 requests.Session 对象。更多信息请参阅 requests 文档
  • http_stream - 启用或禁用 HTTP 流式传输(默认启用)。如果您想将整个文件预加载到内存中,请禁用它。
  • http_timeout - 此超时将用于 requests 会话构建。

stream

源是一个类似文件的 Python 对象。

with open('data.csv') as fp:
    stream = Stream(fp)

text

源是一个包含表格数据的字符串。必须显式设置 schemeformat,因为无法推断它们。

stream = Stream(
    'name,age\nJohn, 21\n',
    scheme='text',
    format='csv'
)

支持的文件格式

在本节中,我们将描述支持的文件格式以及各自的配置选项和操作。一些格式只支持读取操作,而其他格式支持读取和写入。

csv(读取 & 写入)

stream = Stream('data.csv', delimiter=',')

选项

它支持 Python CSV 库的所有选项。有关更多信息,请参阅 它们的文档

xls/xlsx(读取 & 写入)

Tabulator 无法流式传输 xls 文件,因此整个文件将加载到内存中。对于 xlsx 文件,支持流式传输。

stream = Stream('data.xls', sheet=1)

选项

  • sheet:工作表名称或编号(从 1 开始)。
  • workbook_cache:用于处理工作簿缓存的空字典。如果提供,tabulator 将填充字典,包含远程工作簿的 source: tmpfile_path 对。每个工作簿只下载一次,所有临时文件在进程退出时将被删除。默认值:None
  • fill_merged_cells:如果设置为 True,则将取消合并并使用可见值填充所有合并单元格。启用此选项后,解析器不能流式传输数据,而需要将整个文档加载到内存中。
  • preserve_formatting:如果设置为 True,将尝试保留数字和日期单元格的文本格式,并将其作为字符串返回,以符合电子表格中的外观(实验性)。
  • adjust_floating_point_error:如果设置为 True,将纠正 Excel 关于浮点数的处理行为。

ods(只读)

此格式默认不包含在包中。要使用它,请使用以下命令安装带有 ods 扩展的 tabulator$ pip install tabulator[ods]

源应为有效的 Open Office 文档。

stream = Stream('data.ods', sheet=1)

选项

  • sheet:工作表名称或编号(从1开始)

gsheet(只读)

一个公开可访问的 Google 电子表格。

stream = Stream('https://docs.google.com/spreadsheets/d/<id>?usp=sharing')
stream = Stream('https://docs.google.com/spreadsheets/d/<id>edit#gid=<gid>')

sql(读/写)

sqlalchemy 支持的任何数据库 URL。

stream = Stream('postgresql://name:pass@host:5432/database', table='data')

选项

  • table(必需):数据库表名
  • order_by:用于行排序的 SQL 表达式(例如 name DESC

数据包(只读)

此格式默认不包含在包中。要启用它,可以使用以下命令安装 tabulator:pip install tabulator[datapackage]

一个 Tabular Data Package

stream = Stream('datapackage.json', resource=1)

选项

  • resource:资源名称或索引(从0开始)

inline(只读)

可以是列表的列表,或者是一个列表的字典,将列名映射到相应的值。

stream = Stream([['name', 'age'], ['John', 21], ['Alex', 33]])
stream = Stream([{'name': 'John', 'age': 21}, {'name': 'Alex', 'age': 33}])

json(读/写)

包含列表的列表或映射列名到相应值的字典的 JSON 文档(请参见 inline 格式示例)。

stream = Stream('data.json', property='key1.key2')

选项

  • property:包含表格数据的属性的 JSON 路径。例如,考虑 JSON {"response": {"data": [...]}},则 property 应设置为 response.data
  • keyed(写):保存为数组数组(默认)或保存为数组字典(键值)。

ndjson(只读)

stream = Stream('data.ndjson')

tsv(只读)

stream = Stream('data.tsv')

html(只读)

此格式默认不包含在包中。要使用它,请使用以下命令安装带有 html 扩展的 tabulator$ pip install tabulator[html]

位于 HTML 文档内的 HTML 表格元素。

支持简单表格(无合并单元格),以及 td、th、tbody 和 thead 元素的任何合法组合。

通常需要显式指定 foramt='html',因为 Web URL 不总是使用 .html 扩展名。

stream = Stream('http://example.com/some/page.aspx', format='html' selector='.content .data table#id1', raw_html=True)

选项

  • selector:用于指定要提取的 table 元素的 CSS 选择器。默认为 table,它取文档中的第一个 table 元素。如果为空,则假定整个页面是待提取的表格(对某些 Excel 格式很有用)。

  • raw_html:False(默认)提取每个单元格的文本内容。True 返回未修改的内部 html。

自定义文件源和格式

Tabulator 以可扩展性为设计理念,允许您添加对新表格文件格式、方案(例如 ssh)和编写器(例如 MongoDB)的支持。有三个组件允许这样做

  • 加载器
    • 从某个位置(例如 ssh)加载流
  • 解析器
    • 解析某种格式的表格数据流(例如 xls)
  • 编写器
    • 将表格数据写入某个目的地(例如 MongoDB)

在本节中,我们将了解如何编写自定义类以扩展这些组件中的任何一个。

自定义加载器

您可以通过创建自定义加载器来添加对新的方案(例如ssh)的支持。自定义加载器通过从Loader类继承并实现其方法来实现。然后可以通过传递custom_loaders={'scheme': CustomLoader}参数通过Stream使用此加载器来加载数据。

自定义加载器的框架如下

from tabulator import Loader

class CustomLoader(Loader):
  options = []

  def __init__(self, bytes_sample_size, **options):
      pass

  def load(self, source, mode='t', encoding=None):
      # load logic

with Stream(source, custom_loaders={'custom': CustomLoader}) as stream:
  stream.read()

您可以通过查看tabulator.loaders模块来了解加载器是如何实现的示例。

自定义解析器

您可以通过创建自定义解析器来添加对新的文件格式的支持。与自定义加载器类似,自定义解析器通过从Parser类继承并实现其方法来实现。然后可以通过传递custom_parsers={'format': CustomParser}参数通过Stream使用此解析器来解析数据。

自定义解析器的框架如下

from tabulator import Parser

class CustomParser(Parser):
    options = []

    def __init__(self, loader, force_parse, **options):
        self.__loader = loader

    def open(self, source, encoding=None):
        # open logic

    def close(self):
        # close logic

    def reset(self):
        # reset logic

    @property
    def closed(self):
        return False

    @property
    def extended_rows(self):
        # extended rows logic

with Stream(source, custom_parsers={'custom': CustomParser}) as stream:
  stream.read()

您可以通过查看tabulator.parsers模块来了解解析器是如何实现的示例。

自定义写入器

您可以通过创建自定义写入器来添加对以特定格式写入文件的支持。自定义写入器通过从基本Writer类继承并实现其方法来实现。然后可以通过传递custom_writers={'format': CustomWriter}参数通过Stream使用此写入器来写入数据。

自定义写入器的框架如下

from tabulator import Writer

class CustomWriter(Writer):
  options = []

  def __init__(self, **options):
      pass

  def write(self, source, target, headers=None, encoding=None):
      # write logic

with Stream(source, custom_writers={'custom': CustomWriter}) as stream:
  stream.save(target)

您可以通过查看tabulator.writers模块来了解写入器是如何实现的示例。

API参考

cli

cli(source, limit, **options)

命令行界面

Usage: tabulator [OPTIONS] SOURCE

Options:
  --headers INTEGER
  --scheme TEXT
  --format TEXT
  --encoding TEXT
  --limit INTEGER
  --sheet TEXT/INTEGER (excel)
  --fill-merged-cells BOOLEAN (excel)
  --preserve-formatting BOOLEAN (excel)
  --adjust-floating-point-error BOOLEAN (excel)
  --table TEXT (sql)
  --order_by TEXT (sql)
  --resource TEXT/INTEGER (datapackage)
  --property TEXT (json)
  --keyed BOOLEAN (json)
  --version          Show the version and exit.
  --help             Show this message and exit.

Stream

Stream(self,
       source,
       headers=None,
       scheme=None,
       format=None,
       encoding=None,
       compression=None,
       allow_html=False,
       sample_size=100,
       bytes_sample_size=10000,
       ignore_blank_headers=False,
       ignore_listed_headers=None,
       ignore_not_listed_headers=None,
       multiline_headers_joiner=' ',
       multiline_headers_duplicates=False,
       force_strings=False,
       force_parse=False,
       pick_rows=None,
       skip_rows=None,
       pick_fields=None,
       skip_fields=None,
       pick_columns=None,
       skip_columns=None,
       post_parse=[],
       custom_loaders={},
       custom_parsers={},
       custom_writers={},
       **options)

表格数据的流

这是主要的tabulator类。它加载数据源,并允许您流式传输其解析后的内容。

参数

source (str):
    Path to file as ``<scheme>://path/to/file.<format>``.
    If not explicitly set, the scheme (file, http, ...) and
    format (csv, xls, ...) are inferred from the source string.

headers (Union[int, List[int], List[str]], optional):
    Either a row
    number or list of row numbers (in case of multi-line headers) to be
    considered as headers (rows start counting at 1), or the actual
    headers defined a list of strings. If not set, all rows will be
    treated as containing values.

scheme (str, optional):
    Scheme for loading the file (file, http, ...).
    If not set, it'll be inferred from `source`.

format (str, optional):
    File source's format (csv, xls, ...). If not
    set, it'll be inferred from `source`. inferred

encoding (str, optional):
    Source encoding. If not set, it'll be inferred.

compression (str, optional):
    Source file compression (zip, ...). If not set, it'll be inferred.

pick_rows (List[Union[int, str, dict]], optional):
    The same as `skip_rows` but it's for picking rows instead of skipping.

skip_rows (List[Union[int, str, dict]], optional):
    List of row numbers, strings and regex patterns as dicts to skip.
    If a string, it'll skip rows that their first cells begin with it e.g. '#' and '//'.
    To skip only completely blank rows use `{'type': 'preset', 'value': 'blank'}`
    To provide a regex pattern use  `{'type': 'regex', 'value': '^#'}`
    For example: `skip_rows=[1, '# comment', {'type': 'regex', 'value': '^# (regex|comment)'}]`

pick_fields (str[]):
    When passed, ignores all columns with headers
    that the given list DOES NOT include

skip_fields (str[]):
    When passed, ignores all columns with headers
    that the given list includes. If it contains an empty string it will skip
    empty headers

sample_size (int, optional):
    Controls the number of sample rows used to
    infer properties from the data (headers, encoding, etc.). Set to
    ``0`` to disable sampling, in which case nothing will be inferred
    from the data. Defaults to ``config.DEFAULT_SAMPLE_SIZE``.

bytes_sample_size (int, optional):
    Same as `sample_size`, but instead
    of number of rows, controls number of bytes. Defaults to
    ``config.DEFAULT_BYTES_SAMPLE_SIZE``.

allow_html (bool, optional):
    Allow the file source to be an HTML page.
    If False, raises ``exceptions.FormatError`` if the loaded file is
    an HTML page. Defaults to False.

multiline_headers_joiner (str, optional):
    When passed, it's used to join multiline headers
    as `<passed-value>.join(header1_1, header1_2)`
    Defaults to ' ' (space).

multiline_headers_duplicates (bool, optional):
    By default tabulator will exclude a cell of a miltilne header from joining
    if it's exactly the same as the previous seen value in this field.
    Enabling this option will force duplicates inclusion
    Defaults to False.

force_strings (bool, optional):
    When True, casts all data to strings.
    Defaults to False.

force_parse (bool, optional):
    When True, don't raise exceptions when
    parsing malformed rows, simply returning an empty value. Defaults
    to False.

post_parse (List[function], optional):
    List of generator functions that
    receives a list of rows and headers, processes them, and yields
    them (or not). Useful to pre-process the data. Defaults to None.

custom_loaders (dict, optional):
    Dictionary with keys as scheme names,
    and values as their respective ``Loader`` class implementations.
    Defaults to None.

custom_parsers (dict, optional):
    Dictionary with keys as format names,
    and values as their respective ``Parser`` class implementations.
    Defaults to None.

custom_loaders (dict, optional):
    Dictionary with keys as writer format
    names, and values as their respective ``Writer`` class
    implementations. Defaults to None.

**options (Any, optional): Extra options passed to the loaders and parsers.

stream.closed

如果底层流已关闭,则返回True,否则返回False。

返回

bool:是否已关闭

stream.compression

流的压缩(如果没有压缩,则为“no”)

返回

str:压缩

stream.encoding

流的编码

返回

str:编码

stream.format

路径的格式

返回

str:格式

stream.fragment

路径的片段

返回

str:片段

stream.hash

如果可用,返回读取块的计算出的SHA256哈希值

返回

str/None:SHA256哈希

stream.headers

标题

返回

str[]/None:如果可用,则返回标题

stream.sample

返回用作样本的流行。

这些样本行用于内部推断源文件的特征(例如编码、标题等)。

返回

list[]:样本

stream.scheme

路径的方案

返回

str:方案

stream.size

如果可用,则返回读取块的字节计数

返回

int/None:字节计数

stream.source

返回

any:流源

stream.open

stream.open()

打开流以进行读取。

引发

TabulatorException: if an error

stream.close

stream.close()

关闭流。

stream.reset

stream.reset()

将流指针重置为文件开头。

stream.iter

stream.iter(keyed=False, extended=False)

遍历行。

每行以取决于keyedextended参数的格式返回。默认情况下,每行作为值的列表返回。

参数

  • keyed (bool, 可选):当为True时,每个返回的行都将是一个将标题名称映射到当前行中的值的dict。例如,[{'name': 'J Smith', 'value': '10'}]。如果extended为True,则忽略。默认为False。
  • extended (bool, 可选):当为True时,将每行作为包含行号(从1开始)、标题列表和行值列表的元组返回。例如,(1, ['name', 'value'], ['J Smith', '10'])。默认为False。

引发

  • exceptions.TabulatorException:如果流已关闭。

返回

Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]:行本身。格式取决于keyedextended参数的值。

stream.read

stream.read(keyed=False, extended=False, limit=None)

返回行列表。

参数

  • keyed (bool, 可选):参见 :func:Stream.iter
  • extended (bool, 可选):参见 :func:Stream.iter
  • limit (int, 可选):要返回的行数。如果为 None,则返回所有行。默认为 None。

返回

List[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]:行列表。格式取决于 keyedextended 参数的值。

stream.save

stream.save(target, format=None, encoding=None, **options)

将流保存到本地文件系统。

参数

  • target (str):保存流的目标路径。
  • format (str, 可选):流将保存的格式。如果为 None,则从 target 路径中检测。默认为 None。
  • encoding (str, 可选):保存文件的编码。默认为 config.DEFAULT_ENCODING
  • **options:传递给写入器的额外选项。

返回

count (int?):如果可用,则返回已写入的行数。构建索引... 开始生成文档...

Loader

Loader(self, bytes_sample_size, **options)

数据加载器实现该抽象类

加载器继承并实现此类的该方法以添加对新方案(例如 ssh)的支持。

参数

  • bytes_sample_size (int):字节样本大小
  • **options (dict):加载器选项

loader.options

loader.load

loader.load(source, mode='t', encoding=None)

加载源文件。

参数

  • source (str):表格源文件的路径。
  • mode (str, 可选):文本流模式,t(文本)或 b(二进制)。默认为 t
  • encoding (str, 可选):源编码。默认自动检测。

返回

Union[TextIO, BinaryIO]:以文本或二进制方式打开的 I/O 流。

Parser

Parser(self, loader, force_parse, **options)

数据解析器实现的抽象类。

解析器继承并实现此类的该方法以添加对新文件类型的支持。

参数

  • loader (tabulator.Loader):用于读取文件的加载器实例。
  • force_parse (bool):当为 True 时,解析器在解析行时出错时,产生一个空的扩展行元组 (row_number, None, [])。否则,它通过引发异常 tabulator.exceptions.SourceError 停止迭代。
  • **options (dict):加载器选项

parser.closed

表示解析器是否关闭的标志。

返回

bool:是否已关闭

parser.encoding

编码

返回

str:编码

parser.extended_rows

返回扩展行迭代器。

扩展行是包含 (row_number, headers, row) 的元组,

引发

  • SourceError:如果 force_parseFalse 且无法解析行,则引发此异常。否则,返回一个空的扩展行(即 (row_number, None, []))。

返回:Iterator[Tuple[int, List[str], List[Any]]]:包含 (row_number, headers, row) 的扩展行迭代器,其中 headers 是标题名称列表(可以是 None),row 是行值列表。

parser.options

parser.open

parser.open(source, encoding=None)

在文件开头打开底层文件流。

解析器从 tabulator.Loader 实例获取字节或文本流并开始发出项目。

参数

  • source (str):源表的路径。
  • encoding (str, 可选):源编码。默认自动检测。

返回

None

parser.close

parser.close()

关闭底层文件流。

parser.reset

parser.reset()

重置底层流和当前项列表。

在调用 reset() 后,迭代项将从开头开始。

Writer

Writer(self, **options)

由数据写入器实现的抽象类。

编写器继承并实现此类的该方法以添加对新文件目标的支持。

参数

  • **options (dict):编写器选项。

writer.options

writer.write

writer.write(source, target, headers, encoding=None)

将源数据写入目标。

参数

  • source (str):源数据。
  • target (str):写入目标。
  • headers (List[str]):标题名称列表。
  • encoding (str, 可选):源文件编码。

返回

count (int?):如果可用,则返回已写入的行数。

validate

validate(source, scheme=None, format=None)

检查 tabulator 是否能加载源。

参数

  • source (Union[str, IO]):源路径或 IO 对象。
  • scheme (str, 可选):源方案。默认自动检测。
  • 格式 (str, 可选):源文件格式。默认自动检测。

引发

  • SchemeError:不支持的文件方案。
  • FormatError:不支持的文件格式。

返回

bool:tabulator是否能够加载源文件。

TabulatorException

TabulatorException()

所有tabulator异常的基类。

SourceError

SourceError()

源文件无法正确解析。

SchemeError

SchemeError()

不支持的文件方案。

FormatError

FormatError()

不支持的或无效的文件格式。

EncodingError

EncodingError()

编码错误

CompressionError

CompressionError()

压缩错误

IOError

IOError()

本地加载错误

LoadingError

LoadingError()

本地加载错误

HTTPError

HTTPError()

远程加载错误

贡献

该项目遵循开放知识国际编码标准

推荐的开始方法是创建并激活项目虚拟环境。要将包和开发依赖项安装到活动环境中

$ make install

运行带有linting和覆盖率的测试

$ make test

在没有互联网的情况下运行测试

$ pytest -m 'not remote

变更日志

这里仅描述了破坏性和最重要的更改。所有发布版本的完整更改日志和文档可以在格式良好的提交历史中找到。

v1.53

  • 在html解析器中添加了对raw_html提取的支持 (#341)

v1.52

  • 发布了stream.dialect(目前仅适用于csv)

v1.51

  • 添加了实验性的表格发现选项

v1.50

  • 确保headers始终是字符串列表

v1.49

  • 为XLSX格式添加了workbook_cache参数

v1.48

  • 发布了stream.hashing_algorithm属性

v1.47

  • 添加了hashing_algorithm参数

v1.46

  • 修复了多行标题合并
  • 引入了multiline_headers_duplicates标志

v1.45

  • HTML格式:添加了对空选择器的支持 (#321)

v1.44

  • 公开了stream.compression

v1.43

  • 公开了stream.source

v1.42

  • 将格式选项公开到CLI

v1.41

  • 实现了pick_rows参数(与skip_rows相反)

v1.40

  • 实现了stream.save()返回写入的行数

v1.39

  • 实现了JSON写入器 (#311)

v1.38

  • 默认使用chardet进行编码检测。对于cchardetpip install tabulator[cchardet]。由于ccharted在非Linux/Conda安装中造成了大量问题,我们正在将默认设置改回使用chardet

v1.37

  • 即使不存在的文件格式错误,也会引发IOError/HTTPError (#304)

v1.36

  • 实现了blank预设用于skip_rows (#302)

v1.35

  • 为(#293)添加了skip/pick_columns别名

v1.34

  • 添加了multiline_headers_joiner参数 (#291)

v1.33

  • skip_rows中添加了对正则表达式的支持 (#290)

v1.32

  • 添加了跳过列的功能 (#293)

v1.31

  • 添加了xlsx写入器
  • 添加了html读取器

v1.30

  • xlsx解析器添加了adjust_floating_point_error参数

v1.29

  • 实现了stream.sizestream.hash属性

v1.28

  • 添加了SQL写入器

v1.27

  • http/https格式添加了http_timeout参数

v1.26

  • 添加了显示例如Excel工作表或DP资源的名称的stream.fragment字段

v1.25

  • 添加了对s3文件方案的支持(从AWS S3加载数据)

v1.24

  • 添加了对压缩文件对象的兼容性

v1.23

  • stream.headers属性添加了设置器

v1.22

  • 如果提供了skip_rows参数并且数据源顶部有注释,则headers参数现在将使用第一个未跳过的行(见#264)

v1.21

  • 实现了xlsx的实验性preserve_formatting

v1.20

  • 添加了对zip源中指定文件名的支持

v1.19

更新了行为

  • 对于ods格式,现在检测布尔型、整型和datetime原生类型

v1.18

更新了行为

  • 对于xls格式,现在检测布尔型、整型和datetime原生类型

版本1.17

更新了行为

  • 添加了对Python 3.7的支持

版本1.16

添加了新的API

  • skip_rows支持空字符串以跳过第一列空行的行

版本1.15

添加了新的API

  • 将从类似http://example.com?format=csv的URL中提取格式

版本1.14

更新了行为

  • 现在将xls布尔值解析为布尔值而不是整数

版本1.13

添加了新的API

  • skip_rows参数现在支持负数,可以跳过从末尾开始的行

版本1.12

更新了行为

  • 如果选项不被识别,则将发出UserWarning警告而不是抛出异常。

版本1.11

添加了新的API

  • http/https格式添加了http_session参数(现在使用requests
  • 添加了对多行标题的支持:headers参数接受范围,例如[1,3]

版本1.10

添加了新的API

  • 添加了对压缩文件的支持,即在Python3上对zipgz的支持
  • Stream构造函数现在接受一个compression参数
  • http/https方案现在接受一个http_stream标志

版本1.9

改进了行为

  • headers参数允许为键控源设置顺序并选择值

版本1.8

添加了新的API

  • XLS/XLSX/ODS格式支持通过sheet参数传递的表名
  • Stream构造函数接受一个ignore_blank_headers选项

版本1.7

改进了行为

  • datapackage格式基于datapackage@1库进行重置

版本1.6

添加了新的API

  • Stream构造函数的source参数可以是pathlib.Path

版本1.5

添加了新的API

  • Stream构造函数的bytes_sample_size参数

版本1.4

改进了行为

  • 更新了编码名称为规范形式

版本1.3

添加了新的API

  • stream.scheme
  • stream.format
  • stream.encoding

将临时API提升为稳定API

  • Loader(自定义加载器)
  • Parser(自定义解析器)
  • Writer(自定义写入器)
  • validate

版本1.2

改进了行为

  • 自动检测常见的CSV分隔符

版本1.1

添加了新的API

  • xls/xlsx格式添加了fill_merged_cells选项

版本1.0

添加了新的API

  • 发布了Loader/Parser/Writer API
  • Stream添加了force_strings参数
  • Stream添加了force_parse参数
  • Stream添加了custom_writers参数

弃用了API删除

  • 删除了topenTable - 使用Stream代替
  • 删除了Stream参数loader/parser_options - 使用**options代替

临时API已更改

  • 更新了Loader/Parser/Writer API - 请使用更新版本

版本0.15

添加了临时API

  • Stream参数custom_loaders/parsers的不官方支持

项目详情


发布历史 发布通知 | RSS源

下载文件

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

源代码发行版

tabulator-1.53.5.tar.gz (78.0 kB 查看散列)

上传时间 源代码

构建发行版

tabulator-1.53.5-py2.py3-none-any.whl (72.1 kB 查看散列)

上传时间 Python 2 Python 3

由以下机构支持

AWSAWS 云计算和安全赞助商 DatadogDatadog 监控 FastlyFastly CDN GoogleGoogle 下载分析 MicrosoftMicrosoft PSF赞助商 PingdomPingdom 监控 SentrySentry 错误日志 StatusPageStatusPage 状态页面