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

如何使用Python统计文本文件中重复元素的出现次数?

Python统计文本文件中重复ID的出现次数并存储

当然可以用Python轻松实现这个需求,下面是适合新手的简单方案:

核心思路

用Python内置的collections.Counter工具来统计重复元素,它专门用来计数可哈希对象,代码简洁易读。

完整代码示例

from collections import Counter

# 读取目标文本文件并统计ID出现次数
with open('ids.txt', 'r', encoding='utf-8') as file:
    # 逐行读取,去除每行的换行符和空白,过滤空行
    id_list = [line.strip() for line in file if line.strip()]
    # 统计每个ID的次数
    id_count_result = Counter(id_list)

# 打印统计结果(可选,用于验证)
for id_str, count in id_count_result.items():
    print(f"{id_str}: {count}")

# 方式1:将统计结果存储为普通文本文件
with open('id_counts.txt', 'w', encoding='utf-8') as output_file:
    for id_str, count in id_count_result.items():
        output_file.write(f"{id_str} {count}\n")

# 方式2:存储为CSV文件(方便用Excel等表格工具打开)
import csv
with open('id_counts.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    # 写入表头
    writer.writerow(['ID', '出现次数'])
    # 写入统计数据
    for id_str, count in id_count_result.items():
        writer.writerow([id_str, count])

代码说明

  • with open(...):Python推荐的文件操作方式,会自动关闭文件,避免资源泄漏
  • line.strip():去除每行的换行符、空格等多余字符,确保ID格式统一
  • Counter(id_list):一行代码完成计数,返回一个类似字典的对象,键是ID,值是对应次数
  • 存储部分提供了两种常用格式,你可以根据需求选择其中一种

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:01:03