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

Python实现统计字符串中列表元素的出现次数

实现按列表元素统计文本中的出现次数

你可以通过遍历目标字符串列表,逐个统计每个元素在文本中的出现次数,最终将结果整理成列表返回。这里提供两种常见实现方式:

1. 简单子字符串匹配

如果不需要严格匹配完整单词(比如文本中出现"redish"时,会把其中的"red"也算作一次),直接使用字符串的count()方法即可,代码简洁高效:

def some_function(string_list, text):
    return [text.count(item) for item in string_list]

测试你的示例:

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"
print(some_function(string_list, text))  # 输出: [1, 2, 1]

2. 精确单词匹配

如果需要只统计独立的完整单词(避免部分字符匹配的情况),可以借助正则表达式的单词边界\b来实现,同时用re.escape()处理可能包含正则特殊字符的元素:

import re

def some_function(string_list, text):
    count_result = []
    for word in string_list:
        # 构建匹配完整单词的正则模式,re.escape避免特殊字符干扰
        pattern = re.compile(r'\b' + re.escape(word) + r'\b')
        # 查找所有匹配的结果,统计数量
        match_count = len(pattern.findall(text))
        count_result.append(match_count)
    return count_result

如果需要忽略大小写匹配(比如文本中的"Red"也计入统计),可以在编译正则时添加re.IGNORECASE参数:

pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:20:48