python - 将文本文件的特定部分与另一个文本文件进行比较
问题描述
我有一个名为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
解决方案
代码:
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
推荐阅读
- node.js - 如何通过 Firebase Cloud Function 触发 GCP Google Speech API?
- python - 每次捕获一个重复捕获组
- oracle - 重复行 - 交互式网格 - Apex Oracle
- sql - 如何选择满足或超过某些标准的第一个值?
- javascript - 如何在shadow dom中停止传播?
- javascript - 如何在 Javascript 中的一个函数中返回两个函数 - NodeJS 和 ExpressJS
- templates - In HUGO - 如何读取模板中的查询参数
- android - UI 线程的几个处理程序
- html - 用页面高度增加 div 高度
- android - 如何从页面底部到页面顶部?