numpy.fromregex#

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

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

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

参数:
filefile, str, or pathlib.Path

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

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

regexpstr or regexp

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

dtypedtype or list of dtypes

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

encodingstr, optional

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

返回:
outputndarray

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

Raises:
TypeError

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

参见

fromstring , loadtxt

注释

结构化数组的 Dtypes 可以用多种形式指定,但所有形式至少指定数据类型和字段名称. 有关详细信息,请参见 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])