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

如何输出输入字符串的唯一单词?排查get_count_of_unique_words函数异常

问题分析与修复代码

原代码的核心问题

  • get_count_of_unique_words函数错误地遍历单个字符而非拆分后的单词,导致统计的是唯一字母而非唯一单词
  • 函数没有返回值,调用时会输出None
  • word_count用split(" ")拆分文本,遇到多空格会生成空字符串,导致单词数统计错误
  • 未处理大小写差异(比如"Hello"和"hello"会被当成不同单词)
  • 未实现输出重复单词的需求

修复后的完整代码

from collections import Counter

user_text = input("请输入一段文本 --> ")

def word_count(user_text):
    # 用默认split()拆分任意空白字符,自动忽略首尾空格
    return len(user_text.strip().split())

number_of_characters = len(user_text)

def get_word_stats(user_text):
    # 拆分单词并统一转小写,避免大小写差异导致的重复统计
    words = [word.lower() for word in user_text.strip().split() if word.isalpha()]
    word_counts = Counter(words)
    
    # 分离唯一单词和重复单词
    unique_words = [word for word, count in word_counts.items() if count == 1]
    repeated_words = {word: count for word, count in word_counts.items() if count > 1}
    
    return len(unique_words), unique_words, repeated_words

# 获取统计结果
unique_count, unique_list, repeated_dict = get_word_stats(user_text)

print(f"你输入了 {number_of_characters} 个字符")
print(f"你输入了 {word_count(user_text)} 个单词")
print(f"有 {unique_count} 个唯一单词:{', '.join(unique_list)}")
if repeated_dict:
    print("重复的单词及次数:")
    for word, cnt in repeated_dict.items():
        print(f"- {word}: {cnt}次")
else:
    print("没有重复的单词")

关键修改说明

  • 将原get_count_of_unique_words重命名为get_word_stats,扩展功能同时返回唯一单词数量、列表和重复单词字典
  • 拆分单词时用split()替代split(" "),避免多空格问题;同时转小写统一统计规则
  • 添加单词过滤:只保留纯字母的单词(如果需要保留带标点的单词,可以调整过滤逻辑,比如引入string.punctuation处理标点)
  • 函数添加明确的返回值,确保调用时能获取有效数据
  • 新增重复单词的输出逻辑,满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:01:29