需要从用户输入的句子中找到单词的索引位置



编写一个程序,提示用户输入两个输入:一些文本和一个单词。程序输出文本中出现的所有单词的起始索引。如果找不到单词,程序应输出"未找到">

phrase = input('Enter a Sentence: ')
print(phrase)
phrase1 = input('Enter a word from the sentence: ')
words = (phrase.split())
if phrase1 in words:
for w in range(len(words)):
if words[w] == phrase1:
print(words.index(phrase1))
else:
print("Not found.")

这就是我所拥有的。我有用户输入,但没有找到输出,然而,找到第二个输入的每个索引并不是我想做的。下面是它应该是什么样子的例子。如有任何帮助,请提供有助于解释的评论。谢谢。示例1:

Input1: 'my dog and myself are going to my friend'
Input2: 'my'
Output: 0 11 31

示例2:

Input1: 'Programming is fun'
Input2: 'my'
Output: 'not found'

您不应该执行words.index(...),因为这将返回words中的索引,而不是phrase中的索引。

这里有一个替代实现:

phrase = input('Enter a Sentence: ')
print(phrase)
word = input('Enter a word from the sentence: ')
offset = -1
if word in phrase:
while word in phrase[offset+1:]:
offset = phrase.index(word, offset+1)
print(offset)
else:
print('Not found.')

最新更新