2016-07-30 65 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)