首页 > 解决方案 > 将文本文件的特定部分与另一个文本文件进行比较

问题描述

我有一个名为fileOne.txt的文件,如下所示

mystring:
   keyFile: enable
   clusterAuthMode: enable
   authorization: string
   transitionToAuth: boolean
   javascriptEnabled:  enable
   redactClientLogData: boolean

security:
   keyFile: string
   clusterAuthMode: disable
   authorization: string
   transitionToAuth: boolean
   javascriptEnabled:  enable
   redactClientLogData: boolean

test:
   keyFile: disable
   clusterAuthMode: enable
   authorization: string
   transitionToAuth: boolean
   javascriptEnabled: enable
   redactClientLogData: boolean

stack:
   keyFile: string
   clusterAuthMode: enable
   authorization: string
   transitionToAuth: boolean
   javascriptEnabled: enable
   redactClientLogData: enable

还有另一个名为FileTwo.txt的文件,如下所示

security:
   keyFile: string
   clusterAuthMode: enable
   authorization: string
   transitionToAuth: boolean
   javascriptEnabled: enable

我需要检查 FileTwo.txt 的上下文是否存在于 FileOne.txt 中。并打印匹配或不匹配或未找到。

输出 - Matched - security: Matched - keyFile: string NOT Matched - clusterAuthMode: disable Matched - authorization: string NOT Matched - FileString: boolean Matched - javascriptEnabled: enable NOT Found - redactClientLogData: boolean

标签: pythoncompare

解决方案


代码:

import yaml  # pip install pyyaml


def read_yaml(file):
    with open(file, 'r') as f:
        return yaml.safe_load(f)


def compare(a, b):
    for key in a:
        if key not in b:
            # print('NOT Found - {}'.format(key))
            continue

        print('Matched - {}'.format(key))
        for sub_key, sub_value in a[key].items():
            if sub_key not in b[key]:
                print('NOT Found - {}: {}'.format(sub_key, sub_value))
            else:
                if sub_value == b[key][sub_key]:
                    print('Matched - {}: {}'.format(sub_key, sub_value))
                else:
                    print('NOT Matched - {}: {}'.format(sub_key, sub_value))


f1 = read_yaml('FileOne.txt')
f2 = read_yaml('FileTwo.txt')
compare(f1, f2)

输出:

Matched - security
Matched - keyFile: string
NOT Matched - clusterAuthMode: disable
Matched - authorization: string
Matched - transitionToAuth: boolean
Matched - javascriptEnabled: enable
NOT Found - redactClientLogData: boolean

推荐阅读