我正在尝试获取用户键入的单词的位置,但是我只能找到该单词只在句子中出现一次的位置,如果输入的单词多次出现在该单词中,我该如何找到该位置句子?
if varInput in varwords:
print ("Found word")
#prints total number of words
print("The total number of words is: " + str(len(varwords)))#http://stackoverflow.com/questions/8272358/how-do-i-calculate-the-number-of-times-a-word-occurs-in-a-sentence-python
#finds out how many times the word occurs in the sentence
wordOcc = (varwords.count(varInput))
#if word occurence = 1 then print the position of the word
if wordOcc ==1:
pos = varwords.index(varInput)
pos = pos+1
print("the word "+varInput+" appears at position:")
print(pos)
else if wordOcc =>2:
pos1 = varwords.index(varInput)
答案 0 :(得分:0)
.index
方法仅返回第一次出现;它不是一个产生不同值的迭代器。
但是,有一种很容易找到所有事件的方法。您可以遍历单词数组的索引,并添加项目是指定单词的索引:
indexes = [i for i in range(len(sentence)) if sentence[i] == word]
如果没有找到单词,这将以列表或空列表(带len(indexes)==0
)的形式返回所有匹配项。