我的程序的目的是查找句子中单词迭代的位置,并且出现故障的子例程如下所示。在列表中检索字符串的多个迭代位置
def analyse(splitString):
wordToSearch = input("What word are you searching for instances of? ").lower()
for word in splitString:
positionLibrary = ""
positionInSplitString = 0
instances = 0
if word == wordToSearch:
position = splitString.index(word)
positionLibrary += str(position)
print (position, word)
instances += 1
positionInSplitString += 1
return (positionLibrary, instances, wordToSearch)
让“splitString”是句子的列表形式“运动的改变是EVER成正比的动力印象深刻,是在人的右行上,迫使留下了深刻印象。”现在,假设我在splitString中搜索“impressed”,它会返回What word are you searching for instances of? impressed 11 impressed 11 impressed ['the', 'alteration', 'of', 'motion', 'is', 'ever', 'proportional', 'to', 'the', 'motive', 'force', 'impressed', 'and', 'is', 'made', 'in', 'the', 'right', 'line', 'on', 'which', 'that', 'force', 'is', 'impressed'] wordToSearch impressed instances 1 positionLibrary 11
,它告诉我程序以某种方式知道有2个“impressed”实例,但没有将这些实例的数量计入“instances”变量中不可靠并且不起作用)。positionLibrary是为了存储(作为字符串)记录找到的实例的位置,不起作用。我相信这是因为该程序仅返回11 impressed 11 impressed
中所示的“印象深刻”的第一个实例的位置。
现在,我将如何让程序实际返回单词的第一个实例后的任何位置并使“实例”变量起作用?我搜遍了很多,并没有找到解决方案。
建议:更改名称'分析(splitString,wordToSearch)'喜欢的东西'index_multiple更有帮助(迭代,值) '。 – Kupiakos
@ Kupiakos我只是复制/粘贴OP的代码:-)但我同意你的看法,可能会更好。 –