50.Python实现比对功能

今天学长通过 Python 实现了文本对比、文件内容对比、JSON 对比的功能。

代码解析

文本对比

    def compare_texts(self, text1, text2):
        """
        比较两个文本并输出差异。
        :param text1: 第一个文本
        :param text2: 第二个文本
        """

        d = difflib.Differ()
        diff = d.compare(text1.splitlines(), text2.splitlines())
        print('n'.join(diff))

文件内容对比

    def compare_files(self, file1, file2):
        """
        比较两个文本文件的内容。
        :param file1: 第一个文件的路径
        :param file2: 第二个文件的路径
        """

        try:
            with open(file1, 'r', encoding='utf-8'as f1, open(file2, 'r', encoding='utf-8'as f2:
                text1 = f1.read()
                text2 = f2.read()
                self.compare_texts(text1, text2)
        except FileNotFoundError as e:
            print(f"Error: File not found - {e}")
        except Exception as e:
            print(f"An error occurred: {e}")

JSON对比

 def compare_jsons(self, json1, json2, path=''):
        """
        比较两个JSON对象并输出差异。
        :param json1: 第一个JSON对象
        :param json2: 第二个JSON对象
        :param path: 当前路径(用于递归调用)
        """

        if json1 == json2:
            return True
        if type(json1) != type(json2):
            print(f'Type mismatch at {path}{type(json1)} vs {type(json2)}')
            return False
        if isinstance(json1, dict):
            for k in set(list(json1.keys()) + list(json2.keys())):
                new_path = f'{path}.{k}' if path else k
                if k not in json1:
                    print(f'Key {new_path} missing from first object')
                elif k not in json2:
                    print(f'Key {new_path} missing from second object')
                else:
                    self.compare_jsons(json1[k], json2[k], new_path)
        elif isinstance(json1, list):
            if len(json1) != len(json2):
                print(f'Array length mismatch at {path}{len(json1)} vs {len(json2)}')
                return False
            for i in range(max(len(json1), len(json2))):
                new_path = f'{path}[{i}]'
                if i >= len(json1):
                    print(f'Index {new_path} missing from first array')
                elif i >= len(json2):
                    print(f'Index {new_path} missing from second array')
                else:
                    self.compare_jsons(json1[i], json2[i], new_path)
        else:
            print(f'Difference found at {path}{json1} vs {json2}')
            return False

运行测试代码

# 测试文本
text1 = """Hello world
This is a test
Of the text comparison
"""

text2 = """Hello world
This is a test
Of the text comparing
"""


# 测试JSON
json1 = json.loads('{"name": "John", "age": 30, "city": "New York"}')
json2 = json.loads('{"name": "John", "age": 31, "city": "New York"}')

# 创建Comparator实例
comparator = Comparator()

# 比较文本
print("Comparing texts:")
comparator.compare_texts(text1, text2)

# 比较JSON
print("nComparing JSONs:")
comparator.compare_jsons(json1, json2)

# 比较文件
file1 = './resources/file1.txt'
file2 = './resources/file2.txt'
print("nComparing files:")
comparator.compare_files(file1, file2)

运行结果

50.Python实现比对功能

结论

通过本文的介绍,你学会了如何使用 Python 实现学生文本对比、文件内容对比、JSON 对比的功能。


原文始发于微信公众号(学长工具库):50.Python实现比对功能

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/305588.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!