我做了这段代码:
sentence = input("Type in your sentance ").lower().split()
Word = input("What word would you like to find? ")
Keyword = Word.lower().split().append(Word)
positions = []
for (S, subword) in enumerate(sentence):
if (subword == Word):
positions.append
print("The word" , Word , "is in position" , S+1)
但它有2个问题;当找不到用户单词时,我不知道如何编写代码,但是"单词位置在[1,3,6,9]中的位置。 有帮助吗? 感谢
答案 0 :(得分:2)
您的代码有多处错误。我在这里粘贴示例代码供您参考:
from collections import defaultdict
sentence_string = raw_input('Enter Sentence: ')
# Enter Sentence: Here is the content I need to check for index of all words as Yes Hello Yes Yes Hello Yes
word_string = raw_input("Enter Words: ")
# Enter Words: yes hello
word_list = sentence_string.lower().split()
words = word_string.lower().split()
my_dict = defaultdict(list)
for i, word in enumerate(word_list):
my_dict[word].append(i)
for word in words:
print "The word" , word, "is in position " , my_dict[word]
# The word yes is in position [21, 23, 24, 26]
# The word hello is in position [22, 25]
这里的方法是:
sentence_string
此处为单词列表my_dict
以存储word_list
words
中存储的值,对my_dict
进行迭代,以获取索引结果。注意:上面示例中的注释部分基本上是代码的输出。
答案 1 :(得分:0)
使用索引。
a = 'Some sentence of multiple words'
b = 'a word'
def list_matched_indices(list_of_words, word):
pos = 0
indices = []
while True:
try:
pos = list_of_words.index(word, pos)
indices.append(pos)
pos+=1
except:
break
if len(indices):
print(indices)
return indices
else:
print ("Not found")
list_matched_indices(a, b)