Python在列表中查找单词

时间:2016-05-25 12:38:09

标签: python

您好我必须执行一个程序来识别列表中出现单词的所有位置,但是当我运行程序时它不会输出任何内容。 这是我的代码:

sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = input("Choose a word from the sentence above")#this prints out some text with an input 
sentence = sentence.split(" ")# This splits the list 
text = text.upper ()# this makes the text in capital letters
def lookfor ():
    if text in sentence:
        for i in sentence:
            value = sentence.index(sentence)
            print ("Your word has been found in the sentence at the position", value + "and", value )


        else:
            print ("The word that you have typed is not found in the sentence.")

谢谢

2 个答案:

答案 0 :(得分:2)

要回答你的问题,没有任何事情发生,因为你没有调用这个功能。

您的功能还有很多工作要做,但这里有一些常规提示:

1)索引只查找列表中元素的第一个实例

2)你无法确定句子中的单词是否正好两次

3)使用描述性变量名称。例如,for word in sentence在直觉上更有意义

答案 1 :(得分:0)

您可以这样做:

sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = raw_input("Choose a word from the sentence above: ")#this prints out some text with an input 
sentence = sentence.split(" ")# This splits the list 

text = text.upper ()# this makes the text in capital letters
def lookfor (text):
    indexes = [ idx+1 for word, idx in zip(sentence, range(0,len(sentence))) if text == word ]
    print ("Your word has been found in the sentence at these positions", indexes )

    if not indexes:
         print ("The word that you have typed is not found in the sentence.")

lookfor(text)

示例:

ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY
Choose a word from the sentence above: for
('Your word has been found in the sentence at these positions', [8, 14])