比较2个差异文件python中的字符串 [英] Compare string in 2 differents files python

查看:84
本文介绍了比较2个差异文件python中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要您的帮助,因为经过长时间的研究,我没有找到解决我问题的合适方法.

I need your help because after some long research I didn't find the appropriate answer to my problems.

我有2个文件,其中包含一些信息.这些信息中有些相似,其他则不同.第一个文件排序,第二个文件不排序.

I have 2 files which contain some information. Some of this information are similar others are different. The first file is sorted the second one is not.

我尝试使用difflib,但显然不适用于我的情况.

I tried to use the difflib but it doesn't work in my case , apparently.

示例

文件1:

customerID: aa
companyName: AA
contacts: AAAA AAAA <aa@aa.fr>

文件2:

customerID: zz
username: z.z
contacts: ZZZ ZZZ <zz@zz.com>

我需要确定customerID是否相同

I need to find if the customerID is the same

这是我的代码:

import sys
import string
import difflib                                               

def changes(file1, file2):
    # opening the 2 files which we need to compare                                 
    master = open(file1, 'r')
    slave = open(file2, 'r')

    # searching diff                                                               
    diff = difflib.unified_diff(master.readlines(),slave.readlines())
    t = ''.join(diff)
    print (t)




def main(argv=2):
    print (sys.argv[1])
    print (sys.argv[2])
    if argv == 2:
        changes(sys.argv[1], sys.argv[2])
    else:
        print ("This program need 2 files")
        exit (0)
    return 0

    if __name__ == '__main__':
   status = main()
   sys.exit(status)

文件是我本人这样格式化的txt.

Edit : The file are txt that i have formated like this myself.

推荐答案

with open('first.txt', 'r') as first_file:
   for line in first_file:
       data = line.split(":")
       if data[0].trim() == "customerID":
          customer_id  = data[1].trim()
          with open('second.txt', 'r') as second_file:
            for second_file_line in second_file:
            data2 = line.split(":")
            if data2[0].trim() == "customerID":
              if customer_id == data2[1].trim():
                <do your work>

如果文件太大,则在第二个文件中搜索

If your files is too big then searching in second file is

with open('second.txt', 'r') as second_file:
for line in second_file:
    if customer_id in line:
       <do your work>

或者如果文件足够小

if customer_id in open('second.txt').read():
      <do your work>

这篇关于比较2个差异文件python中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆