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

如何统计文本转换列表中匹配关键词的出现次数?

员工记录搜索词次数统计实现方案

现有数据形式

字符串格式(从文本文件转换而来)

EmpRecords='''1,Angelo,Fabregas,South,City;
           2,Fabian,Fabregas,North,City;
           3,Griffin,De Leon,West,City;
           4,John,Doe,East,City;
           5,Jane,Doe',Southville,Town'''

注:原数据最后一行存在格式错误(Doe'多了单引号),处理时需要修正。

列表格式示例

EmpRecords=[1,'Angelo','Fabregas','South','City',
           2,'Fabian','Fabregas','North','City',
           3,'Griffin','De Leon','West','City',
           4,'John','Doe','East','City',
           5,'Jane','Doe','Southville','Town']

功能需求

输入任意搜索词,统计该词在员工记录中的出现次数,示例输出:

Enter word to search: Doe
Same words: 2

实现代码

情况1:处理字符串格式的EmpRecords

# 原始字符串数据
EmpRecords='''1,Angelo,Fabregas,South,City;
           2,Fabian,Fabregas,North,City;
           3,Griffin,De Leon,West,City;
           4,John,Doe,East,City;
           5,Jane,Doe',Southville,Town'''

# 1. 清理数据:去掉多余空格、修正格式错误、移除换行符
cleaned_data = EmpRecords.replace('\n', '').replace(' ', '').replace("Doe'", "Doe")

# 2. 分割成字段列表:先按分号分割记录,再按逗号分割每个字段
records = cleaned_data.split(';')
all_fields = []
for record in records:
    if record:  # 跳过空字符串(最后一个分号分割后可能为空)
        all_fields.extend(record.split(','))

# 3. 输入搜索词并统计次数
search_word = input("Enter word to search: ")
count = all_fields.count(search_word)
print(f"Same words: {count}")

情况2:处理列表格式的EmpRecords

这种情况更简单,直接利用列表的count()方法:

# 原始列表数据
EmpRecords=[1,'Angelo','Fabregas','South','City',
           2,'Fabian','Fabregas','North','City',
           3,'Griffin','De Leon','West','City',
           4,'John','Doe','East','City',
           5,'Jane','Doe','Southville','Town']

# 输入搜索词并统计次数
search_word = input("Enter word to search: ")
# 统一转为字符串处理,兼容所有搜索场景(包括数字ID)
count = str(EmpRecords).count(search_word)
# 若需严格匹配数据类型,可使用以下逻辑:
# count = EmpRecords.count(int(search_word)) if search_word.isdigit() else EmpRecords.count(search_word)
print(f"Same words: {count}")

说明

  • 字符串处理的核心是数据清洗,原始文本可能存在换行、空格和格式错误,需先统一处理为干净的字段列表。
  • 列表处理时,若要严格匹配数据类型(比如数字ID),可根据输入内容判断是否转换类型后再统计;转为字符串统计则更兼容所有搜索场景。

内容的提问来源于stack exchange,提问作者Griffin De Leon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:35:23