2016-07-30 60 views
0

我的程序的目的是查找句子中单词迭代的位置,并且出现故障的子例程如下所示。在列表中检索字符串的多个迭代位置

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中所示的“印象深刻”的第一个实例的位置。

现在,我将如何让程序实际返回单词的第一个实例后的任何位置并使“实例”变量起作用?我搜遍了很多,并没有找到解决方案。

回答

0

您不需要使用index()方法,因为您已经循环了splitString。你只需要一个索引或计数器来跟踪你所处的迭代。为此,您可以使用enumerate

这个怎么样:

def analyse(splitString, wordToSearch): 
    positionLibrary = [j for j, word in enumerate(splitString) if word == wordToSearch] 
    instances = len(positionLibrary) 
    return (positionLibrary, instances) 

splitString = ['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'] 
print analyse(splitString, 'impressed') 
# ([11, 24], 2) 

如果你想使用index(),它可以采取哪些是你应该开始搜索的位置的第二个参数。例如,

print splitString.index('impressed') # 11 
print splitString.index('impressed', 0) # 11 
print splitString.index('impressed', 12) # 24 
+0

建议:更改名称'分析(splitString,wordToSearch)'喜欢的东西'index_multiple更有帮助(迭代,值) '。 – Kupiakos

+0

@ Kupiakos我只是复制/粘贴OP的代码:-)但我同意你的看法,可能会更好。 –

0

如果你喜欢尝试是这样的: -

def index_count_search(sentance, search): 
    searchedList = map(lambda x:x[0], filter(lambda (index, value): search == value, enumerate(sentance.split()))) 
    return (",".join(searchedList), len(searchedList), search) 


wordToSearch = input("What word are you searching for instances of? ").lower() 
print analyse("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".lower(), wordToSearch)