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

修改Python提词器函数解决重复词检索仅返回首条匹配的问题

提词器功能修改实现

解决思路

要实现不回溯的顺序匹配,核心是新增一个检索位置指针,记录当前已经读到的文本位置,后续所有匹配都从该指针位置之后的文本查找,不会再返回之前的区域。

  • 初始时检索起始位置为0,对应文本开头
  • 每次输入单词后,从当前起始位置之后的文本片段查找目标单词
  • 找到匹配后输出下一个单词,同时将检索起始位置更新为当前匹配单词的位置+1
  • 若当前起始位置之后找不到目标单词,提示重试

完整修改代码

def test():
    users_note = """There is a substantial need for child mental health support – 
                    evidence shows that at any given year, 
                    1 in 10 young people will have a diagnosable mental health problem. 
                    Out of these incredibly high numbers, 
                    70% of these young people do not receive adequate mental health support at all, 
                    and of the 30% that do, 
                    only half of them improve. 
                    Though we have evidence-based intervention techniques that work, 
                    we are still relying on outdated technologies and delivery mechanisms. 
                 """
    note_list = users_note.split()
    # 新增当前检索起始位置变量,初始为文本开头
    current_pos = 0
   
    while True:
        for users_try in range(5):
            word_list = input('Enter words you gonna say next: ').split()
            for word in word_list:
                # 从当前位置之后的片段查找目标单词
                try:
                    # 切片查找得到的是相对下标,要加上current_pos得到全局下标
                    match_idx = note_list[current_pos:].index(word) + current_pos
                except ValueError:
                    # 后续片段无该单词,提示重试
                    print('Sorry, try again')
                    continue
                # 不是最后一个单词才输出下一个
                if match_idx + 1 < len(note_list):
                    print(note_list[match_idx + 1])
                else:
                    print('Already reached the end of the text')
                # 更新检索起始位置为匹配位置的下一位
                current_pos = match_idx + 1
        else:
            break

功能验证示例

你可以按照以下步骤测试功能是否符合要求:

  • 第一次输入a,输出substantial,此时检索位置移动到第一次出现a的下一位,后续检索不会再回到该位置之前
  • 继续输入对应单词走到diagnosable之前的a位置时,再次输入a会输出diagnosable
  • 第一次输入these输出incredibly,第二次输入these输出young

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:36:07