[Numpy-discussion] String manipulation

Nils Wagner nwagner@iam.uni-stuttgart...
Tue Jul 21 02:16:55 CDT 2009


On Tue, 21 Jul 2009 02:56:28 -0400
  Pierre GM <pgmdevlist@gmail.com> wrote:
> 
> On Jul 21, 2009, at 2:42 AM, Nils Wagner wrote:
>>
>> Fixed-length fields are quite common e.g. in the area of
>> Finite Element pre/postprocessing.
>> Therefore It would be nice to have a function like
>> line2array in numpy.
>> Comments ?
> 
> Er, there's already something like that:
> np.lib._iotools.LineSplitter
> 
> Initialize it with either a character or an integer as 
>delimiter, and  
> call your instance with a string as input. When you use 
>an integer as  
> delimiter, it corresponds to the length of your field.
> eg:
> >>> s = '-1.000000E+00-1.000000E+00 
>1.000000E+00-1.000000E+00'
> >>> conv = np.lib._iotools.LineConverter(13)
> >>> np.array(conv(s))
> array(['-1.000000E+00', '-1.000000E+00', '1.000000E+00', 
>'-1.000000E 
> +00'],
>       dtype='|S13')
> >>> np.array([float(_) for _ in conv(s)])
> array([-1., -1.,  1., -1.])
> 
> Note that LineSplitter is already used in np.genfromtxt:
> >>> import StringIO
> >>> np.genfromtxt(StringIO.StringIO(s),delimiter=13)
> array([-1., -1.,  1., -1.])
> 
  
Great. I didn't know about that.

Your examples are very useful.

IMHO the examples should be added to

http://www.scipy.org/Cookbook/InputOutput

to attract interest.

Nils


More information about the NumPy-Discussion mailing list