在python中逐行比较两个文件

时间:2016-06-14 09:42:26

标签: python

我想在python中比较两个不同的文件。它们包含具有概率的行,并且每行在文件末尾都有一个id。我需要计算每个id的比率。问题是每一行可能包含不同数量的概率,最终每行记录不同数量的行。我成功地做了一个脚本,只用一行比较两个文件,但我不知道如何为文本中的每一行做这个。到目前为止,这是我的脚本:

#!/usr/bin/python
import math
import operator
f = open('output.txt','w')
file1= open("test.ppx1","r")
file2= open("test.prob1","r")
words = list(file1.read().split())
words2 = list(file2.read().split())
id1=words[-1]
id2=words2[-1]
words.remove(id1)
words2.remove(id2)
words[:]=[x[:12] for x in words]
words2[:]=[x[:12] for x in words2]
words=map(float,words)
words2=map(float,words2)
words=[math.log(y,10) for y in words]
words2=[math.log(y,10) for y in words2]
words=sum(words)
words2=sum(words2)
ratio= words-words2
print >>f, id1,words, words2,ratio

1 个答案:

答案 0 :(得分:1)

您可能希望压缩两个文件的读取内容并对其进行迭代。请注意,当您使用zip时,对于不同行长度的文件,所有文件的长度都是最短的文件长度。见Documentation of zip builtin function

import math


file_list = []

with open("test.ppx1", "r") as file1:
    file_list.append(file1.readlines())

with open("test.prob1", "r") as file2:
    file_list.append(file2.readlines())

with open('output.txt', 'w') as file_out:
    for file1_str, file2_str in zip(*file_list):
        file1_list = file1_str.split()
        file2_list = file2_str.split()
        id1, id2 = file1_list.pop(),  file2_list.pop()
        p1 = map(float, file1_list)
        p2 = map(float, file2_list)
        p1 = map(lambda y: math.log(y, 10), p1)
        p2 = map(lambda y: math.log(y, 10), p2)
        s1, s2 = sum(p1), sum(p2)
        ratio = s1 - s2
        file_out.write("{} {} {} {}".format(id1, s1, s2, ratio))