使用页眉和页脚分析输入流。
header-detail-footer的Python项目详细描述
概述
header_detail_footer模块提供了一种解析输入的方法 包含标题行的iterable(通常是文本文件),未知 数据行数(称为详细信息)和页脚行数。号码 分析开始时必须指定页眉和页脚行的。在那里 可以是零个或多个页眉行,也可以是独立的零个或多个页脚 排。细节行是标题和 页脚。如果一个文件只有页眉和页脚,那么 零细节行。
模块api由一个函数parse()和几个 例外情况。
注意,从未检查每个输入“行”的内容:它们 只是被解析器迭代并返回。他们经常 字符串,但它们可以是任何对象。
典型用法
这段代码显示了parse()函数的简单用法:
>>> from header_detail_footer import parse >>> header, details, footer = parse(['header', 'row 1', 'row 2', 'footer']) >>> header 'header' >>> list(details) ['row 1', 'row 2'] >>> footer() 'footer'
parse()函数
parse()函数接受一个必需的参数,输入 可接受的。有两个可选参数,header_rows和 页脚行。都默认为1。它们表示页眉的数目 和页脚行分别出现在输入中。
parse()返回一个3元组:(header,details,footer)。标题是 标题行(如果有);detail s是返回每个细节的迭代器 row;和footer是可调用的,返回页脚行(如果有)。
对于header和footer(),如果 页眉行或页脚行分别为1。否则,包括 对于0行,它们包含一个列表:
>>> header, details, footer = parse(['row 1', 'row 2', 'footer 1', 'footer 2'], ... header_rows=0, footer_rows=2) >>> header [] >>> list(details) ['row 1', 'row 2'] >>> footer() ['footer 1', 'footer 2']
不需要调用返回的可调用页脚。如果页脚是 调用,必须已用尽详细信息,否则运行时错误为 升起:
>>> header, detail, footer = parse('abc') >>> footer() Traceback (most recent call last): ... RuntimeError: called footer() before details were exhausted
例外情况
在模块级别定义了两个异常:headererror和 页脚错误。注意,这些异常是在解析器()中引发的 方法。它们在遍历头、细节和 或页脚。
头部箭头
由parser()引发
>>> header, details, footer = parse(['row 1'], header_rows=3) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
HeaderError: too few rows for header
与csv文件一起使用
如果CSV文件的标题行包含列名,并且 还有一个页脚行,如果你告诉页眉和页脚 没有标题行。这样,细节迭代器可以 传递给csv.dictreader,它将像往常一样拾取标题行:
>>> import csv # here, the footer row contains a row count >>> _, details, footer = parse(['FRUIT,COLOR', ... 'apple,red', ... 'orange,orange', ... 'rowcount:2'], ... header_rows=0) # specify 0 header rows # pass the details to csv.DictReader. this includes what is now # the csv header row >>> reader = csv.DictReader(details) # print out each row >>> for count, row in enumerate(reader, 1): ... (count, [(key, value) for key, value in sorted(row.items())]) ... (1, [('COLOR', 'red'), ('FRUIT', 'apple')]) (2, [('COLOR', 'orange'), ('FRUIT', 'orange')]) # verify the footer count >>> _, _, footer_count = footer().partition(':') >>> int(footer_count) == count True
更改日志
2.4 2016年10月27日Eric V.Smith
- 重命名分发名称以用下划线替换连字符。这个 名称现在是页眉和页脚(第7期)。
- 移除重命名RPM的黑客(问题5)。
- 始终需要安装工具(第4版)。
- 没有代码更改。
2.3 2014年3月13日Eric V.Smith
- 已将manifest.in添加到manifest.in(问题2)。
- 让bdist_rpm使用包名“python header detail footer” (第3期)。
2.2 2013年12月03日Eric V.Smith
- 添加有关csv文件的文档。
- 将协议错误从valueerror更改为runtimeerror。关闭 比特桶问题1。
2.1 2013年11月16日Eric V.Smith
- 添加manifest.in,使非代码文件在sdist中结束。
2.0 2013年11月15日Eric V.Smith
- 更改了API以返回仅可用于页脚的调用,因为这是 唯一需要在细节用尽后再拖延的事情。
- 更改的名称:现在是指“行”而不是“行”。
1.0条2013年11月15日Eric V.Smith
- 第一个稳定版本。
0.1 2013年11月14日Eric V.Smith
- 初次发布。