簡體   English   中英

與使用python的大文件B相比,從大文件A中查找唯一行的最快方法是什么?

[英]What's the fastest way to find unique lines from huge file A as compared to huge file B using python?

我得到了300、000+行的txt文件A和600、000+行的txt文件B。 現在我要做的是逐行篩選文件A,如果該行未出現在文件B中,那么它將被附加到文件C中。

好吧,問題是,如果我像上面所說的那樣編程,從字面上看需要很長時間才能完成所有工作。 那么,有沒有更好的方法呢?

這應該很快:

with open("a.txt") as a:
    with open("b.txt") as b:
        with open("c.txt", "w") as c:
            c.write("".join(set(a) - set(b)))

請注意,這將忽略A或B中的任何訂單。如果您絕對需要保留A的訂單,則可以使用以下命令:

with open("a.txt") as a:
    with open("b.txt") as b:
        with open("c.txt", "w") as c:
            b_lines = set(b)
            c.write("".join(line for line in a if not line in b_lines))

您可以在內存中保留B嗎? 如果是這樣,請讀取文件B並創建一個包含所有行的索引。 然后逐行閱讀A,並檢查每行是否出現在索引中。

with open("B") as f:
    B = set(f.readlines())

with open("A") as f:
    for line in f.readlines():
        if line not in B:
           print(line)

對python一無所知,但是:如何將文件A按特定順序排序? 然后,您可以逐行瀏覽文件B並進行二進制搜索-效率更高。

將文件B中的所有行讀入set

blines = set(file_b)
for line in file_a:
    if not line in blines:
       append_to_file_c

600k +確實不是那么多數據...

暫無
暫無

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

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