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

如何查找两个文件的共同条目并统计其在第二个文件的出现次数

双文件共同条目查找与条目出现次数统计实现方案

需求说明

实现两个核心功能:

  • 统计第二个文件中每个条目的出现次数
  • 提取两个文件的共同条目

参考测试样本

文件1内容:
Abc1
Abc2
Abc3
Abc1
Abc1

文件2内容:
Abc1
Abc4
Abc3
Abc1

实现方案

方案1:Shell命令行实现(适合快速处理)

统计文件2各元素出现次数

执行命令:

sort 文件2路径 | uniq -c | awk 'BEGIN{print "元素\t出现次数"}{print $2"\t"$1}'

执行后输出结果:

元素    出现次数
Abc1    2
Abc3    1
Abc4    1

提取两个文件的共同条目

执行命令:

grep -Fxf 文件1路径 文件2路径 | sort | uniq

执行后输出结果:

Abc1
Abc3

方案2:Python实现(适合自定义扩展需求)

代码如下:

from collections import Counter

def load_file(file_path: str) -> list:
    with open(file_path, 'r', encoding='utf-8') as f:
        return [line.strip() for line in f if line.strip()]

if __name__ == '__main__':
    # 替换为实际文件路径
    file1 = load_file('./file1.txt')
    file2 = load_file('./file2.txt')

    # 输出文件2统计结果
    print("1、文件2各元素出现次数统计:")
    print(f"{'元素':<8} {'出现次数':<6}")
    count_res = Counter(file2)
    for item, cnt in count_res.items():
        print(f"{item:<8} {cnt:<6}")

    # 输出共同条目
    print("\n2、两个文件的共同条目清单:")
    for item in set(file1) & set(file2):
        print(item)

内容的提问来源于stack exchange,提问作者Mohammed Imran I

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:54:01