使用numpy过滤掉多个注释符号



我正在寻找一种从具有多个注释符号的文件中提取数据的方法。输入文件类似于:

# filename: sample.txt
# Comment 1
# Comment 2
$ Comment 3
1,10
2,20
3,30
4,40
# Comment 4

我似乎只能用下面的代码删除一个注释类型,并且找不到关于如何删除这两个注释类型的任何文档。

import numpy as np
data = np.loadtxt('sample.txt',comments="#") # I need to also filter out '$'

我可以使用其他方法来完成这个任务吗?

使用一个列表来显示注释,例如:

data = np.loadtxt('sample.txt',comments=['#', '$', '@'])

我将创建一个生成器,它将忽略注释,然后将其传递给np.genfromtxt():

gen = (r for r in open('sample.txt') if not r[0] in ('$', '#'))
a = np.genfromtxt(gen, delimiter=',')

对于这种情况,您需要在输入上使用标准python循环,例如:

data = []
with open("input.txt") as fd:
    for line in fd:
        if line.startswith('#') or line.startswith('$'):
            continue
        data.append(map(int, line.strip().split(',')))
print data
输出:

[[1, 10], [2, 20], [3, 30], [4, 40]]

由于您的行只包含注释或数据,因此我在使用numpy处理它之前只是读入文件。注释行将被正则表达式终止。

import re
from StringIO import StringIO
import numpy as np
with open('sample.txt', 'r') as f:
    data = re.sub(r's*[#$].*n', '', f.read())
data = np.genfromtxt(StringIO(data), dtype=int, delimiter=',')

这将为您提供所需的numpy数组data。注意,如果一行(意外地)以一些空格开头,后面跟着一个注释字符,这种方法仍然有效。

我看着numpy。并且不可能使用多个字符进行注释,因为它们使用str.split: https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/npyio.py#L790

我认为你可以逐行加载文件,检查该行是否包含注释,然后将其传递给numpy.fromstring.

如果你想保持完整的loadtxt功率,你可以修改它,使其适合你的需要。正如David Marek所指出的,取消注释的行是这一行

line = asbytes(line).split(comments)[0].strip(asbytes('rn'))

就变成:

for com in comments:
    line = asbytes(line).split(com)[0]
line = line.strip(asbytes('rn'))

您还需要更改L717:

comments = asbytes(comments)

变成:

comments = [asbytes(com) for com in comments]

如果你想保持完全的兼容性,

if isinstance(comments, basestring):
    comments = [comments]

最新更新