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

如何用Python输出文本文件中出现次数大于1的内容?

筛选Python中文本中出现次数超过一次的内容

方法一:修改现有代码实现筛选

你只需要在循环里增加一个判断条件,仅当元素出现次数大于1时再输出:

text = open("dan1.txt").read()
unique = set(text.split())

for word in unique:
    count = text.count(word)
    if count > 1:
        print(f'{word}: {count}')

方法二:用collections.Counter提升效率

如果处理的文本内容较多,上面的方法会重复遍历文本统计次数,效率偏低。可以用Python标准库的Counter工具一次性完成统计,再筛选结果:

from collections import Counter

# 使用with语句自动管理文件关闭,更规范
with open("dan1.txt") as f:
    words = f.read().split()

counts = Counter(words)
# 遍历统计结果,筛选次数>1的元素
for word, count in counts.items():
    if count > 1:
        print(f'{word}: {count}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:49:51