如何使用Python统计.txt文件中各姓名的出现次数
姓名出现次数统计解决方案
以下两种方案都可以轻松处理30万行级别的文本数据,运行耗时基本在1秒以内。
方案1:Shell命令(适用Linux/macOS,Windows可通过WSL/Git Bash运行)
一行命令直接得到结果:
# 基础版,包含空白行统计 sort names.txt | uniq -c | awk '{print $2 " " $1}' > result.txt # 进阶版,自动过滤空白行 grep -v '^[[:space:]]*$' names.txt | sort | uniq -c | awk '{print $2 " " $1}' > result.txt
运行后打开result.txt就是你要的「姓名 计数」格式的输出。
方案2:Python代码(全平台通用,可扩展性强)
直接运行以下代码即可:
from collections import Counter # 读取文件统计姓名出现次数 with open("names.txt", "r", encoding="utf-8") as f: # 逐行读取时自动跳过空行和首尾空白字符 name_count = Counter(line.strip() for line in f if line.strip()) # 写入结果文件 with open("result.txt", "w", encoding="utf-8") as f: # 如需按计数从高到低排序,将下一行改为 for name, cnt in name_count.most_common(): for name, cnt in name_count.items(): f.write(f"{name} {cnt}\n")
如果你的txt文件用的是GBK编码,把代码里的encoding="utf-8"改为encoding="gbk"即可。
内容的提问来源于stack exchange,提问作者user11490432
相关产品推荐
相关产品推荐

