如何用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
相关产品推荐
相关产品推荐

