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

如何修改Python程序实现同频次高频词的合并打印?

解决方案

要实现相同出现次数的单词合并到同一行输出,你需要先将相同次数的单词分组,再按次数从高到低输出每组内容,同时控制输出的单词总数不超过指定数量。以下是修改后的完整代码:

from collections import defaultdict

number_of_words = int(input('Enter how many top words you want to see: '))
stop_words = ["a", "an", "and", "in", "is"]
uniques = []

for word in words:
    # 简化特殊字符检查逻辑
    if word.isalnum() and word not in uniques and word not in stop_words:
        uniques.append(word)

# 原计数逻辑保留
counts = []
for unique in uniques:
    count = 0
    for word in words:
        if word == unique:
            count += 1
    counts.append((count, unique))

# 直接反向排序,替代先sort再reverse的冗余操作
counts.sort(reverse=True)

# 核心修改:按出现次数分组单词
count_to_words = defaultdict(list)
for count, word in counts:
    count_to_words[count].append(word)

# 按次数从高到低输出,同时控制总单词数不超过指定值
remaining = number_of_words
for count in sorted(count_to_words.keys(), reverse=True):
    if remaining <= 0:
        break
    # 取当前组内最多remaining个单词
    selected_words = count_to_words[count][:remaining]
    # 格式化输出同一次数的单词
    print(f'The following words appeared {count} each: {", ".join(selected_words)}')
    remaining -= len(selected_words)

关键修改说明

  1. 分组相同次数的单词:使用defaultdict创建以出现次数为键、对应单词列表为值的字典,把所有次数相同的单词归为一组。
  2. 按次数降序输出:对字典的键(次数)进行降序排序,确保从高频到低频处理每组单词。
  3. 控制输出总数:用remaining变量跟踪还需要输出的单词数量,每次取当前组内不超过remaining的单词,避免输出超过指定数量的单词。

可选优化:用Counter简化计数逻辑

原代码的嵌套循环计数效率较低,你可以使用collections.Counter快速统计单词出现次数,同时跳过停用词和非字母数字的单词,代码会更简洁高效:

from collections import defaultdict, Counter

number_of_words = int(input('Enter how many top words you want to see: '))
stop_words = {"a", "an", "and", "in", "is"}  # 用集合查询速度更快

# 直接过滤并统计符合条件的单词
filtered_words = [word for word in words if word.isalnum() and word not in stop_words]
counts = Counter(filtered_words).most_common()  # 直接得到按次数降序的(单词,次数)列表

# 后续分组和输出逻辑和上面一致
count_to_words = defaultdict(list)
for word, count in counts:
    count_to_words[count].append(word)

remaining = number_of_words
for count in sorted(count_to_words.keys(), reverse=True):
    if remaining <= 0:
        break
    selected_words = count_to_words[count][:remaining]
    print(f'The following words appeared {count} each: {", ".join(selected_words)}')
    remaining -= len(selected_words)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:45:47