我有一個 .csv 檔案(逗號分隔資料),其中一列包含特殊符號,如 α(alpha),而其他列包含字串、int 或浮點數。
我嘗試使用以下代碼讀取此 csv 檔案并將其寫入 .fits 檔案:
fits.writeto(target_file.fits, np.array(Table.read(source_file.csv)))
但是在 α (alpha) 符號位置,代碼向我拋出了一個錯誤:
'ascii' codec can't encode characters in position 2-3: ordinal not in range(128)
我想我必須用 utf-8 編碼一些東西,我嘗試了不同的解決方案但沒有成功。你能幫幫我嗎?
uj5u.com熱心網友回復:
FITS 僅支持 ASCII。您應該能夠執行以下操作,手動編碼為位元組,然后解碼回 unicode:
>>> from astropy.table.table_helpers import simple_table
>>> from astropy.table import Table
>>> t = simple_table()
>>> t['c'] = "α"
>>> t
<Table length=3>
a b c
int64 float64 str1
----- ------- ----
1 1.0 α
2 2.0 α
3 3.0 α
>>> t.convert_unicode_to_bytestring()
>>> t
<Table length=3>
a b c
int64 float64 bytes2
----- ------- ------
1 1.0 α
2 2.0 α
3 3.0 α
>>> t.write('simple_encoded.fits')
>>> t2 = Table.read('simple_encoded.fits')
>>> t2.convert_bytestring_to_unicode()
>>> t2
<Table length=3>
a b c
int64 float64 str1
----- ------- ----
1 1.0 α
2 2.0 α
3 3.0 α
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515561.html
下一篇:Python塊寫入excel
