比较文本文件列出了python

时间:2014-03-07 13:19:10

标签: python list text comparison

我想使用python比较不同文件中的2个列表。为此,我使用以下内容:

truepositives = "a.txt"
with open(truepositives) as file1list:
    file1l = file1list.read().splitlines()

basepairout = "b.txt"

with open(basepairout) as templist:
    templ = templist.read().splitlines()

set1=file1l
set2=templ

truepositives = []
falsepositives = []

for line2 in set2:
    for line1 in set1:
        if (line2.find(line1) != -1):
            if line2 not in truepositives:
                truepositives.append(line2)
        else:
            if line2 not in falsepositives:
                falsepositives.append(line2)

我想把'set2上的所有内容但不在set1中'分配给falsepositives。我的'if'函数运行正常,但我的'else'函数返回整个set2。你知道为什么吗?

2 个答案:

答案 0 :(得分:1)

在你的循环之前保持一个布尔“存在”并将其设置为false ...你的问题是你在set1中的每次迭代进入else语句而不尊重你的条件

它应该是这样的:

for line2 in set2:
    exist = False
    for line1 in set1:
        if (line2.find(line1) == 1):
                exist = True
                break

    if exist == False:
        falsepositives.append(line2)
    else:
        truepositives.append(line2)

答案 1 :(得分:0)