我有一个很大的svmlight格式的文本文件。它包含用分号分隔的由空格分隔的索引(int)和值(float)对组成的字符串。
示例:
1:2 4:12 5:3 ...
2:34 4:2 12:5 ...一个文件可能非常大,并且不可能在numpy数组中一次读取整个文件。
如何以块为单位最有效地读取这样的文件?或者也许更正确的问题是在这种情况下如何有效地创建numpy数组?
现在,我使用以下代码。lines是从文件中读取的行列表。
x = []
for line in lines:
tmp = re.split('[ :]', line)
out = [0] * len(self.__varnames)
for i in range(0, len(tmp), 2):
out[int(tmp[i])] = float(tmp[i+1])
x.append(out)
x = np.asarray(x)与我的其他尝试相比,它是相当快的,但我相信它可以更快。
备注:
1) sklearn包中的load_svmlight_file读取整个文件,不能读取没有前导类标签的文件,这是可选的。
2)我希望找到一个快速的解决方案,而不依赖于外部库(如果存在的话)。但是numpy,scipy当然是允许的。
发布于 2015-12-08 20:14:28
您可以以块为单位生成多行读取。
下面是两种情况的简单解决方案。
def yield_file(infile):
'''(file_path) >> line
A simple generator that yields the lines of a file.
'''
with open(infile, 'r') as f:
for line in f:
yield line
def read_in_chunks(infile, chunk_size=1024):
'''(file_path, int) >> str
Simple generator to read a file in chunks.
'''
with open(infile,'r') as f:
while True:
data = f.read(chunk_size)
if not data:
break
yield data发布于 2015-12-08 20:18:19
您可以更简洁一些,并且不需要正则表达式:
x = []
for line in lines:
out = [0] * len(self.__varnames)
for entry in line.split():
index, value = entry.split(':')
out[int(index)] = float(value)
x.append(out)
x = np.array(x)不知道这样会不会更快。需要测试。
https://stackoverflow.com/questions/34155457
复制相似问题