Skip to main content
 首页 » 编程设计

python之字符串格式问题(括号与下划线)

2024年10月24日30soundcode

我得到了一个包含我所有数据的文本文件

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')])