簡體   English   中英

在 Python 中從非常大的文本文件中刪除重復項的更快方法?

[英]Faster way to remove duplicates from a very large text file in Python?

我有一個非常大的文本文件,其中包含要消除的重復條目。 我不關心條目的順序,因為文件稍后會被排序。

這是我到目前為止所擁有的:

unique_lines = set()
outfile = open("UniqueMasterList.txt", "w", encoding = "latin-1")

with open("MasterList.txt", "r", encoding = "latin-1") as infile:
    for line in infile:
        if line not in unique_lines:
            outfile.write(line)
            unique_lines.add(line)

outfile.close()

它已經運行了30分鍾,還沒有完成。 我需要它更快。 Python 中更快的方法什么?

查找相應的系統命令。 Linux / UNIX中 ,您將使用

uniq MasterList.txt > UniqueMasterList.txt

操作系統通常知道執行這些操作的最佳方法。


評論后

@Mark Ransom提醒我,uniq取決於文件中連續的匹配行。 實現此目的的最簡單方法是對文件進行排序:

sort MasterList.txt | uniq > UniqueMasterList.txt

要在Python中使用與uniq相同的技術,請執行以下操作:

import itertools
with open("MasterList.txt", "r", encoding = "latin-1") as infile:
    sorted_file = sorted(infile.readlines())
for line, _ in itertools.groupby(sorted_file):
    outfile.write(line)

假定整個文件將兩次裝入內存。 或者該文件已經排序,您可以跳過該步驟。

我建議的簡單方法是使用哈希表和哈希表。您可以使用高效的哈希函數對每一行進行哈希處理,然后將其插入哈希表中,並輸出count為1的內容。類似於使用來解決單詞/字母計數問題哈希表。查找僅花費o(1),並且可以將內存使用量限制為恆定量,具體取決於所使用的哈希表的大小。

SPLIT_COUNT = 30


def write_data(t_file, value):
    t_file.write(value)


def calculate_hash(filename, handle_file):

    with open(filename, 'r') as f:

        for line in f:

            write_data(handle_file[hash(line)%SPLIT_COUNT], line)


def generate_file(dir):

    handle_file, files = [], []

    for i in range(SPLIT_COUNT):

        path = dir+"split_"+str(i)

        files.append(path)

        f = open(path, 'w')

        handle_file.append(f)

    return files, handle_file


def close_file(handle_file):

    for i in range(len(handle_file)):

        handle_file[i].close()


def data_uniq(files, new_file):

    dataset = dict()

    n_file = open(new_file, 'w')

    for filename in files:

        f = open(filename, 'r')

        for line in f:

            dataset[line] = 1

        f.close()

        for key in dataset.keys():

            n_file.write(key)

        dataset = {}

    n_file.close()


if __name__ == "__main__":
    filename = './clean.txt'
    generate_dir = './tmp/'
    new_file = './out.txt'
    files, handle_file = generate_file(generate_dir)
    calculate_hash(filename, handle_file)
    close_file(handle_file)
    data_uniq(files, new_file)

暫無
暫無

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

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