【发布时间】:2016-07-30 12:21:53
【问题描述】:
我的程序的目的是找到一个句子中单词迭代的位置,故障子程序如下。
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”成为句子“运动的改变永远与所施加的动力成正比,并且在施加该力的正确直线上产生”的列表形式。现在,假设我在 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 个“印象深刻”的实例,但并未将这些实例的数量计入“实例”变量(这似乎不可靠且不起作用。) positionLibrary,用于存储(作为字符串)找到的实例位置的记录不起作用。我相信这是因为程序只返回“印象”的第一个实例的位置,如 11 impressed
11 impressed 所示。
现在,我如何让程序在单词的第一个实例之后实际返回任何位置并使“实例”变量起作用?我搜索了很远,但没有找到解决方案。
【问题讨论】:
标签: python list subroutine