我得到了一个包含我所有数据的文本文件
data = 'B:/tempfiles/bla.dat'
在文本文件中,我列出了列标题及其类型
col_headers = [('VW_3_Avg','<f8'),('Lvl_Max(1)','<f8')]
然后创建一个包含选项的字典变量:
kwargs = dict(delimiter=',',\
deletechars=' ',\
dtype=col_headers,\
skip_header=4,\
skip_footer=0,\
filling_values='NaN',\
missing_values={'\"NAN\"'}\
)
现在将数据导入到变量数据文件
datafile = scipy.genfromtxt(datafile, **kwargs)
然后我分配数据
VW1 = datafile['VW_3_Avg']
Lv1 = datafile['Lvl_Max(1)']
它与第一个(包含下划线)完美配合,而不是与第二个(括号)完美配合。我收到错误,不仅与此条目有关,而且与所有包含括号的条目有关:
ValueError: field named Lvl_Max(1) not found
当我将文本文件中的括号更改为下划线时,它工作得很好。但我不能说为什么它不允许我使用括号 - 而且我无法更改文本文件格式,因为这是外部生成的。当然,我可以用脚本将括号更改为下划线,但我认为正确执行此操作应该不是什么大问题。在这种情况下,我在哪里以及为什么缺少正确的格式优先级?
最佳答案
该行为已记录在案,NameValidator lib/_iotools.py
中的类解析传入 genfromtxt
的名称:
class NameValidator(object):
"""
Object to validate a list of strings to use as field names.
The strings are stripped of any non alphanumeric character, and spaces
are replaced by '_'. During instantiation, the user can define a list
of names to exclude, as well as a list of invalid characters. Names in
the exclusion list are appended a '_' character.
Once an instance has been created, it can be called with a list of
names, and a list of valid names will be created. The `__call__`
method accepts an optional keyword "default" that sets the default name
in case of ambiguity. By default this is 'f', so that names will
default to `f0`, `f1`, etc.
您的案例中的相关行是字符串被删除任何非字母数字字符
您可以通过在名称中包含其他非字母数字字符的列表上调用 NameValidator.validate
来查看行为:
In [17]: from numpy.lib._iotools import NameValidator
In [18]: l = ["foo(1)","bar!!!","foo bar??"]
In [19]: NameValidator().validate(l)
Out[19]: ('foo1', 'bar', 'foo_bar')
使用 genfromtxt 也一样:
In [24]: datafile = np.genfromtxt("foo.txt", dtype=[('foo!! bar??', '<f8'), ('foo bar bar$', '<f8')], delimiter=",",defaultfmt="%")
In [25]: datafile.dtype
Out[25]: dtype([('foo_bar', '<f8'), ('foo_bar_bar', '<f8')])
关于python - 字符串格式问题(括号或下划线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32538195/