以下是一个高效的Python代码示例,用于比较两个中文文件的内容并提取重复部分到一个文档中:

def compare_files(file1, file2, output_file):
    with open(file1, 'r', encoding='utf-8') as f1, open(file2, 'r', encoding='utf-8') as f2, open(output_file, 'w', encoding='utf-8') as output:
        # 读取文件内容
        content1 = f1.read()
        content2 = f2.read()
        
        # 将内容转换为列表,每个元素为一行文本
        lines1 = content1.split('\n')
        lines2 = content2.split('\n')
        
        # 找到重复的行
        duplicates = set(lines1) & set(lines2)
        
        # 将重复的行写入输出文件
        for line in duplicates:
            output.write(line + '\n')

# 示例用法
compare_files('file1.txt', 'file2.txt', 'output.txt')

请注意,此代码假设输入文件的编码为UTF-8,并且每行文本以换行符分隔。如果文件编码或分隔符不同,请相应地修改代码。

python 两个中文文件内容对比提取重复部分到文档的高效率代码

原文地址: https://www.cveoy.top/t/topic/hUZK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录