繁体   English   中英

使用python从大型文本文件中选择具有特定条件的特定行

[英]select specific lines with specific condition from a large text file with python

我有一个文本文件,其中包含5列和200万行,如下所示:

134   1   2   6    3.45388e-06
135   1   2   7    3.04626e-06
136   1   2   8    4.69364e-06
137   1   2   9    4.21627e-06
138   1   2   10   2.38822e-06
139   1   2   11   1.91216e-06
...
140   1   3   2    5.23876e-06
141   1   3   3    2.83415e-06
142   1   3   7    2.32097e-06
143   1   3   9    6.26283e-06
144   1   3   16   4.22556e-06
...  
145   2   1   2   3.67182e-06
146   2   1   4   4.61481e-06
147   2   1   6   1.1703e-06
...
148   2   2   7   4.61242e-06
149   2   2   21   1.84259e-06
150   2   2   22   4.31435e-06
...
151   2   3   23   4.34518e-06
152   2   3   24   3.76576e-06
153   2   3   25   2.61061e-06
...
154   3   1   2   4.07107e-06
155   3   1   7   4.83971e-06
156   3   1   8   3.43919e-06
...
157   3   2   29   6.27991e-06
158   3   2   30   7.44213e-06
159   3   2   31   9.56985e-06
...
160   3   3   32   1.38377e-05
161   3   3   33   1.62724e-05
162   3   3   34   9.85653e-06
...

第二列显示每一层的数量,在每一层中,我都有一个矩阵,其中第3列和第4列是该层中行和列的数量,最后一列是我的数据。首先,我想提出一个条件,如果第二列相等到一个数字(例如3),将这种情况的所有行打印到另一个文件中,我使用以下代码进行此操作:

    with open ('C:\ Python \ projects\A.txt') as f,  open('D:\ Python \New_ projects\NEW.txt', 'w') as f2:
      # read the data from layer 120 and write these data in New.txt file
      for f in islice (f,393084, 409467):
        f2.write(f)
a = np.loadtxt('D:\ Python \New_ projects\NEW.txt

但是问题在于,对于每一层,我都必须转到文件,并找到每一层的第一行和最后一行,然后将其放入islice中,这需要很长时间,因为文件太大了,我该怎么办?说column [2] = 4将行保存为新文本?

*****,然后我需要另一个条件,即对于Column [2] = 4,如果20 <= column [3] <= 50
80 <= column [4] <= 120->将这些行保存在另一个文件中。

使用grep函数并使用过滤后的数据创建另一个文件,grep的速度足以处理文件

如前所述, grep可能是使用正则表达式的快速非Python解决方案,例如:

grep -E '^[0-9]+\s+[0-9]+\s+2\s' testgrep.txt > output.txt

它将所有行保存在文件output.txt ,第三行带有2 有关该模式的详细信息,请参见https://regex101.com/r/j5EfEE/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM