2016-05-15 10 views
0

このコードを作成して、人に文章を入力するように指示しました。 その後、その文章に単語を入力します。 その後、コードが出力単語がである位置。リスト内で同じ2つの単語の位置を見つける

print("Type a sentence here") 
sentence = input("") 

sentence = sentence.split() 
print("Now type a word in that sentence.") 
word = input('') 

if word in sentence: 
    print("I found",word,"in your sentence.") 
else: 
    print("That word is not in your sentence.") 

print(sentence.index(word)) 

は私が午前問題は、彼らが文の中で同じ単語のうちの2つを置けば、それは最初のものだけを出力していることであるだろう。どうぞお助けください。

答えて

0

組み込みのenumerateを使用すると、リストsentenceのすべての単語を対応する位置に関連付けることができます。次に、リスト内包語を使用して、リスト内のすべての語句を取得します。

print([i for i, j in enumerate(sentence) if j == word]) 

さらにいくつかの考慮事項は、多分あなたは正しい句読点と大文字があなたのマッチングをつまずかないように、ケースを下げ、あなたの言葉に一致するように試みる前に、句読点を削除するには、あなたの文章を変換したいということでしょう。さらに、有効にするために''input()にする必要はありません。プロンプトなしの空のinput()が問題ありません。

+0

うまく動作します。ありがとうございました。 – Jake

0

このPBは、このスクリプトによって解決される:

import re 
print("Type a sentence here") 
sentence = raw_input("") 
print("Now type a word in that sentence.") 

word = raw_input('') 
words = re.sub("[^\w]", " ", sentence).split() # using re 


position = 1 
list_pos = [] 
for w in words : 
    if w == word: 
     print position 
     list_pos.append(position) 
    position += 1 
if list_pos: 
    print("I found",word,"in your sentence.") 
else: 
    print("That word is not in your sentence.") 
print list_pos 
関連する問題