You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python或PowerShell对比两个大文本文件并输出匹配行?

两个文本文件取交集并写入输出文件的实现方法

Python 实现

利用集合的高效交集特性,适合处理大文件场景:

# 读取文件内容,去掉空行并转成集合(自动去重)
with open('Text1.txt', 'r', encoding='utf-8') as f1:
    set1 = set(line.strip() for line in f1 if line.strip())

with open('Text2.txt', 'r', encoding='utf-8') as f2:
    set2 = set(line.strip() for line in f2 if line.strip())

# 取交集并写入output.txt
with open('output.txt', 'w', encoding='utf-8') as out_f:
    # 若不需要排序,去掉sorted()可进一步提升速度
    for line in sorted(set1 & set2):
        out_f.write(line + '\n')

PowerShell 实现

避开效率较低的Compare-Object,用哈希集合处理大文件更高效:

# 读取文件内容,去空行后转哈希集合(自动去重)
$set1 = [System.Collections.Generic.HashSet[string]]::new((Get-Content -Path "Text1.txt").Trim() | Where-Object { $_ })
$set2 = [System.Collections.Generic.HashSet[string]]::new((Get-Content -Path "Text2.txt").Trim() | Where-Object { $_ })

# 筛选交集并写入文件
$intersection = $set1 | Where-Object { $set2.Contains($_) }
$intersection | Out-File -Path "output.txt" -Encoding utf8

内容的提问来源于stack exchange,提问作者unamic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:27:02