2016-05-15 89 views
0

所以我創建了這個代碼來要求一個人輸入一個句子。然後他們在那句話中輸入一個單詞。 然後代碼將輸出字中的位置。找到列表中相同的兩個單詞的位置

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)) 

我遇到的問題是,如果他們在句子中把同一個詞兩個它只輸出的第一個。請你幫忙。

回答

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 
相關問題