3

我有一个 c++ 程序,它生成许多数据文件,每个文件都包含三列。现在,在这些数据文件中的每一个中,第三列都会有一些异常条目-nan。如何编写脚本以打开这些数据文件中的每一个并找到第三列具有的nan所有行并删除所有这些行?是否可以在 bash 或 python 中编写一个可以做到这一点的脚本?例子:

100   0.1    15.8334
100   0.2    16.7895
100   0.3     -nan
100   0.4    15.8543
100   0.5      -nan

在这个文件中,我希望删除第 3 行和第 5 行,以便我的文件看起来像

100   0.1    15.8334
100   0.2    16.7895
100   0.4    15.8543
4

3 回答 3

3

像(在bash中)这样的东西:

for file in files ;do
  grep -v -- -nan file > file.$$ && mv file.$$ file
done

不过可能应该在代码中清理它。

于 2012-07-12T13:14:58.203 回答
2
sed -i -e '/-nan/d' datafile.txt

要对多个文件进行操作,可以将“datafile.txt”替换为匹配所有文件的 glob,或使用 for 循环

for file in data1.txt data2.txt data3.txt; do
    sed -i -e '/-nan/d' $file
done

或者find命令:

find . -name "data*.txt" -exec sed -i -e '/-nan/d' {} +
于 2012-07-12T13:23:05.680 回答
1

这是基本机制:

with open('yourfile.txt') as fin, open('yourfile_output.txt', 'w') as fout:
    for line in fin:
        try:
            c1, c2, c3 = line.split()
            if c3 != '-nan':
                fout.write(line)
        except ValueError as e:
            pass # Handle cases where number of cols != 3

然后把它放在一个函数中并使用 glob.iglob 来重新输入匹配文件名的列表并循环......

另一个可能的选择只是为了完整性:

from math import isnan

with open('yourfile.txt') as fin, open('yourfile_output.txt', 'w') as fout:
    for line in fin:
        try:
            c1, c2, c3 = map(float, line.split())
            if not isnan(c3):
                fout.write(line)
        except ValueError as e:
            pass # Handle cases where number of cols != 3
于 2012-07-12T13:15:17.733 回答