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

如何使用Python按重复次数对文本文件内容进行降序排序

可行实现代码

方法1:使用collections.Counter(最简实现)

from collections import Counter

# 你已完成文件读取,这里假设读取后的内容存储在列表lines中,读取示例如下(可跳过)
with open('abc.txt', 'r', encoding='utf-8') as f:
    lines = [line.strip() for line in f if line.strip()]  # strip去掉换行和空白行,避免统计空内容

# 统计每个内容的出现次数
count_dict = Counter(lines)

# 排序规则:首先按次数降序,次数相同则按字符本身升序(匹配你给出的预期输出顺序)
sorted_items = sorted(count_dict.items(), key=lambda x: (-x[1], x[0]))

# 格式化输出
for char, cnt in sorted_items:
    unit = "time" if cnt == 1 else "times"
    print(f"{char} - {cnt} {unit}")

方法2:不依赖额外模块,用原生字典统计

如果你不想用collections模块,可以用原生字典实现统计逻辑:

# 读取文件步骤同上
with open('abc.txt', 'r', encoding='utf-8') as f:
    lines = [line.strip() for line in f if line.strip()]

count_dict = {}
for char in lines:
    count_dict[char] = count_dict.get(char, 0) + 1

# 排序和输出逻辑和方法1完全一致
sorted_items = sorted(count_dict.items(), key=lambda x: (-x[1], x[0]))
for char, cnt in sorted_items:
    unit = "time" if cnt == 1 else "times"
    print(f"{char} - {cnt} {unit}")

关键逻辑说明

  • 排序的核心是sorted函数的key参数:lambda x: (-x[1], x[0]),其中-x[1]表示按次数的负值排序(等价于原次数降序),第二位的x[0]表示次数相同时按字符的字典序升序,刚好匹配你给出的预期输出中a在d前面的要求。
  • 输出时做了单复数判断,和你的预期输出格式完全对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:39:03