如何在列表中查找单词

时间:2016-05-20 08:31:31

标签: python string python-3.x indexing

所以我的程序会要求用户输入短语 WITHOUT 标点符号,程序将返回其在列表中的位置。

def Detection():
        print(list.index(find))
        find_found=list.index(find)
        list[find_found]="hide"
list = input("Enter a phrase without punctuation:")
print(list) 
list = list.split(" ")
list = [element.lower() for element in list]
find=input("what word must be found?")
find=find.lower()
if find in list:
for find in list:
    Detection()
else:
    print("its not in the list.")

2 个答案:

答案 0 :(得分:0)

l = [“输入”,'a','短语']

l.index( 'a')的

如果列表中没有单词则返回索引抛出ValueError异常。

获取重复项的索引

sorted_list = sorted(l)
first_ind = sorted_list.index("enter")
last_ind = len(sorted_list) - sorted_list[::-1].index("enter") - 1
indexes = range(first_ind, last_ind + 1)

答案 1 :(得分:0)

我在这里找到了一条路。

sentence =input("phrase to be shortened: ")
print (sentence)
text = input("Choose a word from the sentence above: ")
sentence = sentence.upper()
sentence = sentence.split(" ")
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)