如何找到一个python程序列出位置和显示以及错误消息

时间:2016-10-06 15:51:19

标签: python

我做了这段代码:

sentence = input("Type in your sentance ").lower().split()
Word = input("What word would you like to find? ")
Keyword = Word.lower().split().append(Word)
positions = []

for (S, subword) in enumerate(sentence):
    if (subword == Word):
        positions.append
        print("The word" , Word , "is in position" , S+1)

但它有2个问题;当找不到用户单词时,我不知道如何编写代码,但是"单词位置在[1,3,6,9]中的位置。 有帮助吗? 感谢

2 个答案:

答案 0 :(得分:2)

您的代码有多处错误。我在这里粘贴示例代码供您参考:

from collections import defaultdict

sentence_string = raw_input('Enter Sentence: ')
# Enter Sentence: Here is the content I need to check for index of all words as Yes Hello Yes Yes Hello Yes

word_string = raw_input("Enter Words: ")
# Enter Words: yes hello

word_list = sentence_string.lower().split()
words = word_string.lower().split()

my_dict = defaultdict(list)
for i, word in enumerate(word_list):
     my_dict[word].append(i)

for word in words:
    print "The word" , word, "is in position " , my_dict[word]

# The word yes is in position  [21, 23, 24, 26]
# The word hello is in position  [22, 25]

这里的方法是:

  1. 将您的句子分解为sentence_string此处为单词列表
  2. 将单词字符串分解为单词列表。
  3. 创建字典my_dict以存储word_list
  4. 中所有单词的索引
  5. 根据words中存储的值,对my_dict进行迭代,以获取索引结果。
  6. 注意:上面示例中的注释部分基本上是代码的输出。

答案 1 :(得分:0)

  

使用索引。

a = 'Some sentence of multiple words'
b = 'a word'


def list_matched_indices(list_of_words, word):
    pos = 0
    indices = []
    while True:
        try:
            pos = list_of_words.index(word, pos)
            indices.append(pos)
            pos+=1
        except:
            break
    if len(indices):
        print(indices)
        return indices
    else:
        print ("Not found")

list_matched_indices(a, b)