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

「MOTIONの変更がIMPRESSED原動力TO EVER比例し、力が印加されていることをどのRIGHT LINEで作られて」「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に示すように、「感銘を受けた」最初のインスタンスの位置を返すだけなので、これが信じています。

ここで、プログラムが実際に単語の最初のインスタンスの後に任意の位置を返し、 "インスタンス"変数を動作させるにはどうすればよいですか?私は広範囲に調査し、解決策を見いださなかった。

答えて

0

すでにsplitStringでループしているので、index()メソッドを使用する必要はありません。あなたはあなたがどこにいるかを追跡するインデックスまたはカウンタが必要です。そのためには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

推奨: 'index_multiple(反復可能な、値)のような、より便利なものに' '(splitString、wordToSearch)を分析の名前を変更します'。 – 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) 
関連する問題