python:创建unicode字符串的字符集

2024-09-30 16:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用python3中的astropy.fits替换FITS文件中的一些数据。为了与原始FITS文件保持一致,我想写一个numpy.chararraydtype='<U100'

我试过使用numpy.chararray(x),其中x是一个字符串列表,我得到了*** TypeError: 'str' object cannot be interpreted as an integer

我非常困惑,因为我认为在python 3中所有的字符串都是unicode,而在我的理解中'<U100'是unicode。我想知道我做错了什么


Tags: 文件数据字符串numpy列表unicodepython3dtype
2条回答

FITS标准不处理unicode。在astropy.fits中,当您编写时,它将尝试编码为ASCII。当你阅读一个FITS文件时,有一种神奇的方法可以让ASCII bytes看起来像str

简而言之,如果您试图直接处理存储在FITS中的数据,则需要使用bytes。例如:

In [8]: s = np.array(['hello', 'world'])                                        

In [9]: np.char.encode(s, 'ascii')                                              
Out[9]: array([b'hello', b'world'], dtype='|S5')

如果没有更多关于您试图更改的内容的详细信息,很难说,但是假设您使用的是FITS表,最简单的方法可能是使用表API

下面是一个示例表:

>>> from astropy.table import Table
>>> t = Table({'a': ['a', 'b', 'c']})
>>> t.write('table.fits')

您可以使用Table.read加载它,然后像修改任何字符串数组一样修改它。它将正确地处理重新编码

>>> t = Table.read('table.fits')
>>> t
<Table length=3>
  a   
bytes1
   
     a
     b
     c
>>> t['a'] = ['d', 'e', 'f']
>>> t.write('table.fits', overwrite=True)
>>> t = Table.read('table.fits')
>>> t
<Table length=3>
  a   
bytes1
   
     d
     e
     f

如果您想直接使用较低级别的FITS界面,也可以。在大多数情况下,不必手动构造chararray(这是一个内部实现细节):

>>> from astropy.io import fits
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('d',), ('e',), ('f',)], dtype=(numpy.record, [('a', 'S1')]))
>>> hdul[1].data['a']
chararray(['d', 'e', 'f'], dtype='<U1')
>>> hdul[1].data['a'] = ['g', 'e', 'h']
>>> hdul[1].data['a']
chararray(['g', 'e', 'h'], dtype='<U1')
>>> hdul.writeto('table.fits', overwrite=True)
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('g',), ('e',), ('h',)], dtype=(numpy.record, [('a', 'S1')]))

相关问题 更多 >