2016-05-15 55 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 
相关问题