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

tir*_*ire 8 python numpy

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

# filename: sample.txt
# Comment 1
# Comment 2
$ Comment 3
1,10
2,20
3,30
4,40
# Comment 4
Run Code Online (Sandbox Code Playgroud)

我似乎只能使用以下代码删除一个注释类型,但无法找到有关如何删除这两个注释类型的任何文档.

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

有没有其他方法可以用来完成这个?

小智 6

只需使用列表进行评论,例如:

data = np.loadtxt('sample.txt',comments=['#', '$', '@'])
Run Code Online (Sandbox Code Playgroud)


Fre*_*ihl 2

对于这种情况,您需要诉诸标准 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
Run Code Online (Sandbox Code Playgroud)

输出:

[[1, 10], [2, 20], [3, 30], [4, 40]]
Run Code Online (Sandbox Code Playgroud)