I'm working with transferring some Matlab code to Python. I'm relatively new to Python and am unsure of a Python equivalent of Matlab's textscan
method. Any help would be greatly appreciated.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Extract matrix elements using a vector of column i
- Evil ctypes hack in python
Example of conversion of MATLAB's
textscan
to Python + NumPy'snp.loadtxt
:Let our data file
results.csv
contain:Matlab code:
Python + NumPy code:
For more info on types, see Data type objects (dtype).
you have to look for Numpy and py2mat. If my understanding of textscan() is correct you could just use
open()
If your results are more complicated than simple delimited text, such as if there are other, useless bits of text mixed in, then you can use Numpy's
fromregex
function to replacetextscan
.fromregex
lets you read in based on a regular expression, with groups (parts surrounded by()
) as the values.So for example say you have lines like this:
And you want to get the value numbers (not the field names):
You can do
The
[\d\.]+
matches any number, including decimal places, and the()
tells numpy to use that result as a value. You can also specify more complicated dtypes, such as having different columns have different types, as well as specifying column names to give a structured array. That is covered in the documentation.However, it is more complicated than other approaches when dealing with simple delimited or fixed-width data.
If you're translating Matlab to Python, I'll assume you're already using NumPy.
In that case, you can use
np.loadtxt
(if no values are missing) ornp.genfromtxt
(if there are missing values: I'm not sure whether Matlab'stextscan
handles that).Give us a few more details if you need more help!