从配置文件中删除制表符
Delete tab character from config files
我正在使用这个函数来读取配置文件。
import numpy as np
stream = np.genfromtxt(filepath, delimiter = '\n', comments='#', dtype= 'str')
它工作得很好,但我有一个问题:制表符。
即
输出
['\tvalue1 ', ' 1'] ['\t'] ['value2 ', ' 2']
有没有办法忽略这个特殊字符?
我的解决方案是这样的:(它适用于我的目的,但有点 "ugly")
result = {}
for el in stream:
row = el.split('=',1)
try:
if len(row) == 2:
row[0] = row[0].replace(' ','').replace('\t','') #clean the elements from not needed spaces
row[1] = row[1].replace(' ','').replace('\t','')
result[row[0]] = eval(row[1])
except:
print >> sys.stderr,"FATAL ERROR: '"+filepath+"' missetted"
logging.exception(sys.stderr)
sys.exit('')
讲解员似乎可以使用 numpys genfromtext 分配多个分隔符或注释。我建议去别处看看。尝试 https://docs.python.org/2/library/configparser.html. Here's a link with a quick example so you can get a feel for how to work with the module https://wiki.python.org/moin/ConfigParserExamples
要用任何东西替换制表符:
stream = [x.replace('\t','') for x in stream]
或者用单个 space 替换制表符,然后删除重复的 spaces:
stream = [' '.join(x.replace('\t',' ').split()) for x in stream]
删除空字符串 (source):
stream = filter(None, stream)
我正在使用这个函数来读取配置文件。
import numpy as np
stream = np.genfromtxt(filepath, delimiter = '\n', comments='#', dtype= 'str')
它工作得很好,但我有一个问题:制表符。
即 输出
['\tvalue1 ', ' 1'] ['\t'] ['value2 ', ' 2']
有没有办法忽略这个特殊字符?
我的解决方案是这样的:(它适用于我的目的,但有点 "ugly")
result = {}
for el in stream:
row = el.split('=',1)
try:
if len(row) == 2:
row[0] = row[0].replace(' ','').replace('\t','') #clean the elements from not needed spaces
row[1] = row[1].replace(' ','').replace('\t','')
result[row[0]] = eval(row[1])
except:
print >> sys.stderr,"FATAL ERROR: '"+filepath+"' missetted"
logging.exception(sys.stderr)
sys.exit('')
讲解员似乎可以使用 numpys genfromtext 分配多个分隔符或注释。我建议去别处看看。尝试 https://docs.python.org/2/library/configparser.html. Here's a link with a quick example so you can get a feel for how to work with the module https://wiki.python.org/moin/ConfigParserExamples
要用任何东西替换制表符:
stream = [x.replace('\t','') for x in stream]
或者用单个 space 替换制表符,然后删除重复的 spaces:
stream = [' '.join(x.replace('\t',' ').split()) for x in stream]
删除空字符串 (source):
stream = filter(None, stream)