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

如何统计文本中指定字符串出现次数?以统计"the"出现2次为例

修正字符串出现次数统计代码

需求:统计文本 "there are a lot of the cats" 中 "the" 的出现次数,预期返回结果为2。

原代码存在的问题

  • 函数名text与全局变量text重名,导致函数内部的text被覆盖为函数对象,遍历逻辑完全失效
  • 函数内部逻辑偏离需求:循环遍历对象错误,判断条件"ou" in text与统计"the"毫无关联
  • 直接访问函数内部的局部变量count,会触发未定义错误
  • 最后打印未定义的变量i,触发报错
  • 虽然使用了re.findall获取匹配结果,但后续代码未正确利用该结果完成统计

修正后的代码方案

方案一:利用正则表达式(简洁高效)

import re
text = "there are a lot of the cats"
# 通过findall匹配所有"the",返回列表的长度即为出现次数
count = len(re.findall("the", text))
print(count)  # 输出:2

方案二:自定义函数实现

text = "there are a lot of the cats"

def count_word_occurrence(target_text, word):
    count = 0
    start_index = 0
    # 循环查找目标字符串,直到找不到为止
    while True:
        index = target_text.find(word, start_index)
        if index == -1:
            break
        count += 1
        # 更新起始索引,避免重复匹配同一位置
        start_index = index + len(word)
    return count

# 调用函数统计"the"的出现次数
result = count_word_occurrence(text, "the")
print(result)  # 输出:2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:21