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

Python单词频率统计实现:字符串分割问题求助

问题描述

需要编写word_frequency函数,要求:

  • 输入字符串包含大小写ASCII字母,统计时不区分大小写(用lower()处理)
  • 非字母字符作为单词分隔符
  • 完成词频统计,示例输入print(word_frequency("Idk, Idc, Idk, Idf"))需输出{'idk': 2, 'idc': 1, 'idf': 1}

当前编写的代码无法正确分割字符串,代码如下:

def word_frequency(text):
    f = {}
    pendens = ""

    for s in text:
        if s.isalpha():
            pendens += s
        else:
            pendens = pendens.lower()
            if pendens != " ":
                if f.get(pendens, -1) != -1:
                    f[pendens] += 1
                else:
                    f[pendens] = 1
    pendens = pendens.lower()
    if pendens != " ": 
        if f.get(pendens, -1) != -1:
            f[pendens] += 1
        else:
            f[pendens] = 1
    return f

print(word_frequency("Idk, Idc, Idk, Idf"))       
print(word_frequency("Idk,+Idc,Idk;;-;Idf"))     
print(word_frequency("help me please"))  
问题分析与改进代码

原代码的核心问题:

  1. 遇到非字母字符处理完当前单词后,没有清空pendens,导致后续字母会继续追加到旧的单词上
  2. 判断单词是否有效时用了pendens != " ",这是错误的,应该判断pendens是否为空字符串(pendens != "")
  3. 统计词频的逻辑冗余,可简化处理

改进后的代码:

def word_frequency(text):
    freq = {}
    current_word = ""
    
    for char in text:
        if char.isalpha():
            current_word += char.lower()  # 直接转小写,避免后续重复处理
        else:
            if current_word:  # 如果当前单词不为空
                freq[current_word] = freq.get(current_word, 0) + 1
                current_word = ""  # 清空,准备下一个单词
    # 处理循环结束后剩下的最后一个单词
    if current_word:
        freq[current_word] = freq.get(current_word, 0) + 1
    return freq

# 测试用例
print(word_frequency("Idk, Idc, Idk, Idf"))       # 输出: {'idk': 2, 'idc': 1, 'idf': 1}
print(word_frequency("Idk,+Idc,Idk;;-;Idf"))     # 输出: {'idk': 2, 'idc': 1, 'idf': 1}
print(word_frequency("help me please"))          # 输出: {'help': 1, 'me': 1, 'please': 1}
关键改进点说明
  • 遍历字符时直接转小写,减少重复调用lower(),逻辑更清晰
  • 遇到非字母字符时,先检查当前单词是否有效(非空),统计后立即清空current_word,避免后续字符追加错误
  • 用freq.get(current_word, 0) + 1简化词频统计逻辑,替代复杂的条件判断
  • 循环结束后必须处理最后一个单词(如果输入以字母结尾,循环里的非字母分支不会触发)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:10:41