簡體   English   中英

比較2個txt文件並根據1個或文件中不存在的內容創建一個新的txt文件

[英]Comparing 2 txt files and creating a new txt file from what is absent in 1 or the files

我有2個txt文件,一個是水果列表,另一個是許多數據列表,其中每行都嵌入一個水果,如下所示:

文件1:

apple
orange
grape
banana
pear

文件2

Brian b7890 apple orchard autumn
Sue c7623 grape vineyard summer
Richard z4501 grapefruit citrusGrove autumn
Mary m8123 pear orchard autumn

我需要從文件2中提取相應的水果不出現在文件1中的行,並將其寫入新的文本文件。 在文件2的此示例中,唯一符合條件的行是:

Richard z4501 grapefruit citrusGrove autumn

請注意:我已經給出了這個示例,因為文件1中出現的“葡萄”一詞是葡萄柚一詞的一部分,其中排除了一些更簡單的提取方法。

我首先將每個文件的每一行放入列表中:

f = open('ListOfFruits.txt')
listOfFruits = [line.strip() for line in open('ListOfFruits.txt')]
f.close()

a = open('AllFruitData.txt')
AllFruitData = [line.strip() for line in open('AllFruitData.txt')]
a.close()

i=0
x=0

while x < len(listOfFruits):
    if listOfFruits[i] not in allFruitData[x]:
        i=i+1
        #then check against allFruitData again
        #continue until the end of listOfFruits
        #if no match is found then add the line allFruitData[x] to a new txt file
   x=x+1  

我已經嘗試過使用for循環,while循環和if語句的各種方法,但是似乎總是卡在語法上。 我試圖想象代碼在2個輪子相互旋轉的同時工作,而1個是靜止的,另一個一直旋轉直到找到匹配項。 如果找到匹配項,則固定輪將在1個位置移動,而移動輪將重置。 如果固定輪在動輪上找不到匹配項,則該數據將進入一個新的籃子。 這將繼續進行,直到固定輪上的所有位置都已被移動輪所遍歷。

怎么樣使用set 然后,您可以使用集合差異 一個簡單的實現可以是(如果水果始終位於第二個文件的每一行的第三位)

with open('listOfFruits.txt', 'r') as f:
    fruits = set([line.rstrip() for line in f])
with open('allFruitData.txt', 'r') as f:
    data = {}
    for line in f:
        fruit = line.rstrip().split()[2]
        data[fruit] = line

fruits_not_in_file = set(data.keys()) - fruits
with open(outfile, 'w') as f:
    for fruit in fruits_not_in_lile:
        f.write(data[fruit])

編輯:

如果水果可以出現在任何列中,那么如果您不知道哪些單詞是水果,則此問題會更加困難。 但是,如果您只想打印出不包含任何命名水果的行,那還不錯:

with open('listOfFruits.txt', 'r') as f:
    fruits = set([line.rstrip() for line in f])

with open('outfile.txt', 'w') as outf, open('allFruitData.txt', 'r') as inf:
    for line in inf:
        words = set(line.rstrip().split())
        # you can replace this `if` with `if fruits & words == set()`
        if not fruits & words:
            outf.write(line)

首先將所有水果讀為一組。 然后,對於數據文件中的每一行,我們測試該行中的任何單詞是否在結果集中。 如果交集為空,則將該行打印到輸出文件中。 如果該行在某處包含水果,則繼續進行下一行。

請注意,這不會將'grape''grapefruit'匹配,因為它會根據您選擇的分隔符(看起來像是space或\\t )來分割行。

這應該可以完成工作(假設file2中的結果始終是第三項):

def compare_fruits():

    files = ["file1", "file2"]
    file_list = []

    for file in files:
        with open("filepath/%s.txt", % file "r") as f:
            file_list.append(f.readlines())

    list1 = [i.strip() for i in file_list[0]]
    list2 = [i.split()[2] for i in file_list[1]]

    diff = []

    for i in list1:
        for j in list2:
            if j not in i:
                diff.append(j)

    with open("filepath/file3.txt", "w") as f: #creates file3 if doesn't exist
        for i in diff:
            f.write(i + '\n')

暫無
暫無

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

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