跳转到主要内容

从文件中提取样本行。

项目描述

从已编写的文件中提取样本行。

安装

按照以下方式安装。

pip install sample-lines

如何

查看帮助以获取文档信息。

sample-lines -h
usage: Randomly select lines from a file. [-h] [--sample-size N]
                                          [--method {simple-random,systematic}]
                                          [--repeat REPEAT]
                                          file

positional arguments:
  file

optional arguments:
  -h, --help            show this help message and exit
  --sample-size N, -n N
                        Number of lines to emit
  --method {simple-random,systematic}, -m {simple-random,systematic}
                        Sampling method
  --repeat REPEAT, -r REPEAT
                        Number of repetitions for systematic sampling

样本是带有替换和按行长度加权的。选择行的概率与上一行的长度成比例。这使我们能够快速采样,但这种方法仅适用于文件行长度合理一致或至少行长度没有周期性变化的情况。

速度如何

考虑这个1GB的CSV文件。

$ wc big-file.csv
 2388430 27673790 1071895374 big-file.csv

运行wc花费了三秒钟。

time wc big-file.csv
 2388430 27673790 1071895374 big-file.csv

real    0m3.789s
user    0m3.560s
sys     0m0.190s

下面是解析整个文件所需的时间。

$ time python3 -c 'for line in open("big-file.csv"): pass'

real    0m2.892s
user    0m2.641s
sys     0m0.245s

sample-lines要快得多。这里是一个简单的40行随机样本,

$ time sample-lines -n 40 -m simple-random big-file.csv > /dev/null

real    0m0.136s
user    0m0.113s
sys     0m0.018s

一个40行的系统样本,

$ time sample-lines -n 40 -m systematic -r 4 big-file.csv > /dev/null

real    0m0.148s
user    0m0.122s
sys     0m0.019s

以及重复的系统样本,重复4次,每次10行,总共40行。

$ time sample-lines -n 10 -m systematic -r 4 big-file.csv > /dev/null

real    0m0.175s
user    0m0.140s
sys     0m0.025s

上述示例中的大部分时间都花在了加载Python和各种模块上;打印帮助的时间几乎与运行样本的时间一样长。

$ time sample-lines -h > /dev/null

real    0m0.157s
user    0m0.129s
sys     0m0.021s

所以即使是非常大的样本运行起来也很快。

$ time sample-lines -n 2000 -m systematic -r 50 big-file.csv > /dev/null

real    0m2.695s
user    0m2.435s
sys     0m0.231s

替代方案

如果您想从流中采样,请使用sample

项目详情


下载文件

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

源代码分发

sample-lines-0.0.4.tar.gz (2.6 kB 查看哈希值)

上传时间: 源代码

支持