我正在尝试将大文本数据加载到numpy数组。Numpy的loadtxt和genfromtxt对as不起作用
['#','!','C']
开头的注释行n*value
,其中n
是重复的整数,value
是浮点数据。在因此,我尝试使用readlines()
读取文本文件,然后使用Numpy的loadtxt
将数据转换为Numpy数组。在
对于读取和替换,我尝试使用正则表达式(re
模块),但无法使其正常工作。但是下面的Python代码正在工作。我的问题是什么是最有效率和Python式的方式来做这件事?在
如果是RegEx,那么在readlines()
list对象中执行以下查找和替换的正确RegEx代码是什么:
lines = ['1 2 3*2.5 3 6 1*.3 8 \n', '! comment here\n', '1*1 2.0 2*2.1 3 6 0 8 \n']
for l, line in enumerate(lines):
if line.strip() == '' or line.strip()[0] in ['#','!','C']:
del lines[l]
for l, line in enumerate(lines):
repls = [word for word in line.strip().split() if word.find('*')>=0]
print repls
for repl in repls:
print repl
line = line.replace(repl, ' '.join([repl.split('*')[1] for n in xrange(int(repl.split('*')[0]))]))
lines[l] = line
print lines
输出如下:
^{pr2}$根据评论,我编辑了如下Python代码:
in_lines = ['1 2 3*2.5 3 6 1*.3 8 \n', '! comment here\n', '1*1 2.0 2*2.1 3 6 0 8 \n']
lines = []
for line in in_lines:
if line.strip() == '' or line.strip()[0] in ['#','!','C']:
continue
else:
repls = [word for word in line.strip().split() if word.find('*')>=0]
for repl in repls:
line = line.replace(repl, ' '.join([float(repl.split('*')[1]) for n in xrange(int(repl.split('*')[0]))]))
lines.append(line)
print lines
Python道
使用python令人敬畏的功能特性和列表理解来代替:
输出:
^{pr2}$又快又小的Python道
此解决方案使用生成器而不是列表,这样您就不必在内存中加载整个文件。注意两个习语的用法:
with open("name") as file
这将在退出块后清理文件句柄。
for line in file
这将使用生成器迭代文件中的行,而无需在内存中加载整个文件。
这给了我们:
输出:
相关问题 更多 >
编程相关推荐