首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当同一个单词多次出现时,跟踪搜索文本中的位置。

当同一个单词多次出现时,跟踪搜索文本中的位置。
EN

Stack Overflow用户
提问于 2021-11-17 23:56:18
回答 1查看 55关注 0票数 0
代码语言:javascript
复制
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()
   
    while True:
        for users_try in range(5):
            word_list = input('Enter words you gonna say next: ').split()
            for word in word_list:
                if word not in note_list:
                    print('Sorry, try again')
                else:
                    print(note_list[note_list.index(word) + 1])
        else:
            break

这个功能本质上是一个提词器。当用户以任何顺序输入一个或多个单词时,该函数将在每个用户的输入单词后面打印该单词。然而,当一个输入词在预先生成的文本中发生多次时,有一个边缘情况;函数总是在第一次出现时打印单词。如何修改此功能以跟踪用户在预先生成的文本中的输入单词位置?例如:

对于"a"第一次出现在预先制作的文本中:

代码语言:javascript
复制
Enter words you gonna say next: a

substantial

如果用户已经在文本中传递了这一点,那么第二次输入"a"

代码语言:javascript
复制
Enter words you gonna say next: a

diagnosable

对于"these"第一次出现在预先制作的文本中:

代码语言:javascript
复制
Enter words you gonna say next: these

incredibly

如果用户已经在文本中传递了这一点,那么第二次输入"these"

代码语言:javascript
复制
Enter words you gonna say next: these

young

换句话说,一旦已经搜索到一个单词,程序就应该继续在文本中继续前进。我该如何做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2021-11-18 00:02:05

只要您不打算让用户在文本中倒退,那么一个简单的解决方案就是在您使用时修改note_list

代码语言:javascript
复制
if word not in note_list:
    print('Sorry, try again')
else:
    note_list = note_list[note_list.index(word) + 1:]
    print(note_list[0])

这使得不可能“重复”一个特定的词,无论这个词是唯一的还是不唯一的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70013001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档