鱼C论坛

 找回密码
 立即注册
12
返回列表 发新帖
楼主: pythonsrj

[已解决]字符串索引

[复制链接]
发表于 2020-3-8 06:33:39 | 显示全部楼层
  1. source = '长白山上有一品红,一品红在长白山上'
  2. search_items = ['长白山', '一品红']

  3. def find_index(source, search_item):
  4.     result = []
  5.     start = 0
  6.     while True:
  7.         index = source.find(search_item, start)
  8.         if index == -1:
  9.             return result

  10.         start = index + len(search_item)
  11.         result.append(index)        
  12.    
  13. idx = []
  14. for item in search_items:
  15.     result = find_index(source, item)
  16.     idx.extend(result)

  17. print(idx)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-3-8 11:57:00 | 显示全部楼层
contents = ['长白山上有一品红,一品红在长白山上长白山']
mention_list = ["长白山", "一品红"]
label_mention = {}
for content in contents:
    for mention in mention_list:
        kb_id = []
        for j in range(len(content) - len(mention) + 1):
            if content[j: j + len(mention)] == mention:
                kb_id.append(j)
                label_mention[mention] = kb_id
print(label_mention)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-6 17:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表