MCPcopy Create free account
hub / github.com/numpy/numpy / fromregex

Function fromregex

numpy/lib/npyio.py:1639–1734  ·  view source on GitHub ↗

r""" Construct an array from a text file, using regular expression parsing. The returned array is always a structured array, and is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields of the structured array.

(file, regexp, dtype, encoding=None)

Source from the content-addressed store, hash-verified

1637
1638@set_module('numpy')
1639def fromregex(file, regexp, dtype, encoding=None):
1640 r"""
1641 Construct an array from a text file, using regular expression parsing.
1642
1643 The returned array is always a structured array, and is constructed from
1644 all matches of the regular expression in the file. Groups in the regular
1645 expression are converted to fields of the structured array.
1646
1647 Parameters
1648 ----------
1649 file : path or file
1650 Filename or file object to read.
1651
1652 .. versionchanged:: 1.22.0
1653 Now accepts `os.PathLike` implementations.
1654 regexp : str or regexp
1655 Regular expression used to parse the file.
1656 Groups in the regular expression correspond to fields in the dtype.
1657 dtype : dtype or list of dtypes
1658 Dtype for the structured array; must be a structured datatype.
1659 encoding : str, optional
1660 Encoding used to decode the inputfile. Does not apply to input streams.
1661
1662 .. versionadded:: 1.14.0
1663
1664 Returns
1665 -------
1666 output : ndarray
1667 The output array, containing the part of the content of `file` that
1668 was matched by `regexp`. `output` is always a structured array.
1669
1670 Raises
1671 ------
1672 TypeError
1673 When `dtype` is not a valid dtype for a structured array.
1674
1675 See Also
1676 --------
1677 fromstring, loadtxt
1678
1679 Notes
1680 -----
1681 Dtypes for structured arrays can be specified in several forms, but all
1682 forms specify at least the data type and field name. For details see
1683 `basics.rec`.
1684
1685 Examples
1686 --------
1687 >>> from io import StringIO
1688 >>> text = StringIO("1312 foo\n1534 bar\n444 qux")
1689
1690 >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything]
1691 >>> output = np.fromregex(text, regexp,
1692 ... [('num', np.int64), ('key', 'S3')])
1693 >>> output
1694 array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
1695 dtype=[('num', '<i8'), ('key', 'S3')])
1696 >>> output['num']

Callers

nothing calls this directly

Calls 7

asbytesFunction · 0.90
asstrFunction · 0.90
openMethod · 0.45
dtypeMethod · 0.45
readMethod · 0.45
compileMethod · 0.45
closeMethod · 0.45

Tested by

no test coverage detected