我正在尝试编写一个脚本来读取具有名为 的字段的特定 hdf5 文件,该文件具有ElementAbundance
化学元素的 araays 分数值。
这就是我正在做的,我打开 hdf5 文件,我列出了该文件中的字段。如果文件有ElementAbundance
,它将检查我要求输入的元素field
是否在elements
数组中。如果它在数组中,那么我想将我要求的元素作为单个字符串返回。
我在其他地方检查过,其中的字段ElementAbundance
是
elements = ['Carbon', 'Helium', 'Hydrogen', 'Iron', 'Magnesium', 'Neon', 'Nitrogen', 'Oxygen', 'Silicon']
import h5py
from particleType import partTypeNum # This is another file that is unimportant in regards to my question
# Only necessary if gas (0) particle type
def loadElement(basePath,snapNum,partType,field=None):
result = {}
# This uses the above module to associate keys words with the letter 0
ptNum = partTypeNum(partType)
gName = "PartType" + str(ptNum)
# making sure fields is not a single element
if isinstance(field, basestring):
field = [field]
# begin by opening the h5py file
with h5py.File(snapPath(basePath,snapNum),'r') as f:
# header = dict( f['Header'].attrs.items() )
# nPart = getNumPart(header)
# This creates a list for all the fields in the HDF5 file
field_list = []
for i in f[gName].keys():
field_list.append(str(i))
# This will check if the file has a "ElementAbundance" header
for i in enumerate(field_list):
# if the string is not inside the list, we raise an exception
if "ElementAbundance" not in field_list:
raise Exception("Particle type ["+str(ptNum)+"] does not have a field of elements")
# If it is, we extract the chemical elements from inside the element abundance field.
else:
g = f[gName]['ElementAbundance'] # file contains elements
elements = []
for j in g.keys():
elements.append(str(j))
# now for looping the lists values with their index
for i,element in enumerate(elements):
# if the element field is inside the elements list, we retrieve that element as a string
if field == element:
the_element = str(elements[i])
return the_element
# if their is a ElementAbundance field but the asked for field element is not in that list, raise and exception.
else:
raise Exception("Element type ["+str(field)+"] not found in element abundance list.")
f.close()
# testing to see if the above for loop returns a single string
return the_element
现在我然后测试它是否返回字符串“Hydrogen”,但我返回异常: Exception: Element type [['Hydrogen']] not found in element abundance list.
这很奇怪,因为Hydrogen
应该在elements
我制作的列表中。此外,引发的异常应该返回['Hydrogen']
not [['Hydrogen']]
。
如果他们是我可以添加的任何其他信息,请告诉我!
如果您将函数调用为:
loadElement(basePath,snapNum,partType,field='Hydrogen')
然后 'Hydrogen' 变成了一个单项列表:
if isinstance(field, basestring):
field = [field]
当您迭代元素列表时,您正在迭代字符串并将它们与['Hydrogen']
列表匹配,因此找不到匹配项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句