【问题标题】:Compare string in 2 differents files python比较2个不同文件python中的字符串
【发布时间】:2015-10-13 13:13:17
【问题描述】:

我需要你的帮助,因为经过长时间的研究,我没有找到解决问题的合适答案。

我有 2 个包含一些信息的文件。其中一些信息是相似的,而另一些则不同。 第一个文件已排序,第二个未排序。

我尝试使用 difflib,但显然在我的情况下它不起作用。

例子

文件 1:

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

文件 2:

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

我需要查找customerID是否相同

这是我的代码:

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。

【问题讨论】:

  • 您是否尝试过使用正则表达式从两个文件中提取 customerID 信息并进行比较?
  • 我不确定你想做什么。是否要检查第一个文件中的所有 custermID 是否也存在于第二个文件中?
  • 我想检查两个文件中的customerID是否相同,只打印不一样的
  • maccinza 不,我读了很多关于 python 的文章,而且我的大部分研究都不适合使用正则表达式,我不知道如何使用正则表达式
  • 我建议您阅读docs.python.org/2/library/re.html 并构建一个正则表达式以从每个文件中过滤掉您想要的信息。

标签: python string file compare difflib


【解决方案1】:
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>

如果您的文件太大,那么在第二个文件中搜索是

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>

【讨论】:

  • 是的,我试过了,但也没有按照我的意愿正常工作。
  • 你能告诉我你在尝试时遇到的问题吗?
  • 我没有遇到任何技术问题,只是当我使用这种方法时,它会像这样打印: customerID: ZZZ customerID: WWWW customerID: XXXX 而且我只需要比较 customerID 的值两个文件之间
  • 如果我理解正确,您只需要像 zzz,wwww,xxxx 这样的客户 ID,因此您可以拆分该行字符串或使用 regx。
  • 就是这样!我只需要比较两个文件中 customerID 的值。
猜你喜欢
  • 2016-09-04
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
相关资源
最近更新 更多