comparing two text files and remove duplicates in python

前端 未结 2 1691
情深已故
情深已故 2021-01-07 07:24

I have two text files, file1 and file2.

File1 contains a bunch of random words, and file2 contains words that I w

2条回答
  •  独厮守ぢ
    2021-01-07 08:08

    get the words from each:

    f1 = open("/path/to/file1", "r") 
    f2 = open("/path/to/file2", "r") 
    
    file1_raw = f1.read()
    file2_raw = f2.read()
    
    file1_words = file1_raw.split()
    file2_words = file2_raw.split()
    

    if you want unique words from file1 that aren't in file2:

    result = set(file1_words).difference(set(file2_words))
    

    if you care about removing the words from the text of file1

    for w in file2_words:
        file1_raw = file1_raw.replace(w, "")
    

提交回复
热议问题