numpy.fromregex#

numpy.fromregex(file, regexp, dtype, encoding=None)[源代码]#

使用正则表达式解析,从文本文件构造数组.

返回的数组始终是结构化数组,它由文件中正则表达式的所有匹配项构成.正则表达式中的组会转换为结构化数组的字段.

参数:
filefile, str, 或 pathlib.Path

要读取的文件名或文件对象.

在 1.22.0 版本发生变更: 现在接受 os.PathLike 实现.

regexpstr 或 regexp

用于解析文件的正则表达式.正则表达式中的组对应于 dtype 中的字段.

dtypedtype 或 dtypes 列表

结构化数组的 Dtype;必须是结构化数据类型.

encodingstr, optional

用于解码输入文件的编码.不适用于输入流.

返回:
outputndarray

输出数组,包含 file 中与 regexp 匹配的内容部分. output 始终是结构化数组.

提出:
TypeError

dtype 不是结构化数组的有效 dtype 时.

参见

fromstring , loadtxt

注释

结构化数组的 Dtype 可以用多种形式指定,但所有形式至少指定数据类型和字段名称.有关详细信息,请参见 basics.rec .

示例

>>> import numpy as np
>>> from io import StringIO
>>> text = StringIO("1312 foo\n1534  bar\n444   qux")
>>> regexp = r"(\d+)\s+(...)"  # match [digits, whitespace, anything]
>>> output = np.fromregex(text, regexp,
...                       [('num', np.int64), ('key', 'S3')])
>>> output
array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
      dtype=[('num', '<i8'), ('key', 'S3')])
>>> output['num']
array([1312, 1534,  444])