簡體   English   中英

python - 如何從包含特定字母表的大型文本文件(> 60GB)中刪除所有行?

[英]How to remove all lines from a large text file (>60GB) that contains a specific alphabet in python?

我有一個大文本文件 (>60GB),我想從中刪除某些行。

文本文件包含:

352_0M, 352_1M,  0.913
500_1F, 452_0M,  0.500
870_0M, 400_1F,  0.980
601_1F, 470_0M,  0.630
845_0M, 900_1M,  0.456
100_1F, 250_0F,  0.123
...

我想刪除第一列或第二列或兩者中包含“F”字母的所有行。 預期的輸出是:

352_0M, 352_1M,  0.913
845_0M, 900_1M,  0.456

如何在python中做到這一點?

with open('input_file','r') as inf:
    with open('output_file','w') as outf:
        for line in inf:
            if not any('F' in x for x in line.split(',', 2)[:2]):
                outf.write(line)

numpy 的解決方案

import numpy as np
A = np.loadtxt('input_file',dtype=str,delimiter=', ')
id1 = [ 'F' not in a for a in A.T[0]]
id2 = [ 'F' not in a for a in A.T[1]]
B = A[np.bitwise_and(id1,id2)]
np.savetxt('file_out',B)

編輯:感謝 Marcos 和 AMC 的評論。 雖然我提出的解決方案要快一點,但我糾正了自己:不是! Błotosmętek 的解決方案在性能和 RAM 使用方面都要好得多。 我檢查了一個 600 GB 的測試文件,建議的 numpy 解決方案比 Błotosmętek 的解決方案差兩倍。

嘗試用python將文件拆分成多個部分,然后搜索特定的單詞。 處理大文件非常困難,因為它需要巨大的 RAM 容量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM