回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>下面这个最小的示例显示了我如何尝试将字符串写入netcdf文件。应为单个字符串(var1)。但是,对于多字符字符串(var2),只考虑前几个字符。在</p>
<pre><code>from netCDF4 import <a href="https://www.cnpython.com/pypi/dataset" class="inner-link">dataset</a>
strs1 = ['a', 'b']
strs2 = ['aa', 'bb']
ds = Dataset('test.nc','w')
ds.createDimension('x', 2)
var1 = ds.createVariable('var1', 'S1', (u'x',))
var1[:] = strs1
print strs1,var1[:]
var2 = ds.createVariable('var2', 'S1', (u'x',))
var2[:] = strs2
print strs2,var2[:]
ds.close()
</code></pre>
<p>输出如下所示</p>
^{pr2}$
<p>我试图添加第二个维度,但这也没有给出期望的结果。
有人能解决这个问题吗?在</p>
<p>编辑:使用第一个答案,我可以使用第二个维度,使其工作如下</p>
<pre><code>import netCDF4
import numpy as np
strs1 = ['a', 'b']
strs2 = ['aa', 'bb']
ds = netCDF4.Dataset('test.nc','w')
ds.createDimension('x', 2)
ds.createDimension('strlen', 2)
var1 = ds.createVariable('var1', 'S1', (u'x',))
var1[:] = strs1
print strs1,var1[:]
var2 = ds.createVariable('var2', 'S1', (u'x',u'strlen'))
var2[:] = netCDF4.stringtochar(np.array(strs2))
print strs2,netCDF4.chartostring(var2[:])
ds.close()
</code></pre>
<p>给出这个输出:</p>
<pre><code>['a', 'b'] ['a' 'b']
['aa', 'bb'] ['aa' 'bb']
</code></pre>