【问题标题】:Can't get program to print "not in sentence" when word not in sentence当单词不在句子中时,无法让程序打印“不在句子中”
【发布时间】:2016-09-19 18:25:35
【问题描述】:

我有一个程序要求输入一个句子,然后要求输入一个单词,然后告诉你那个单词的位置:

sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")

for i, word in enumerate(words):
     if askedword == word :
          print(i+1)
    #elif keyword != words :
         #print ("this not")

但是当我编辑它说如果输入单词不在句子中时,我无法让程序正常工作,然后打印“this is not in the sentence”

【问题讨论】:

    标签: python python-3.x words enumerate sentence


    【解决方案1】:

    列表是序列,因此您可以在它们上使用the in operation 来测试words 列表中的成员资格。如果在里面,用words.index找到句子里面的位置:

    sentence = input("enter sentence: ").lower()
    askedword = input("enter word to locate position: ").lower()
    words = sentence.split(" ")
    
    if askedword in words:
        print('Position of word: ', words.index(askedword))
    else:
        print("Word is not in the given sentence.")
    

    带样本输入:

    enter sentence: hello world
    
    enter word to locate position: world
    Position of word: 1
    

    而且,一个错误的案例:

    enter sentence: hello world
    
    enter word to locate position: worldz
    Word is not in the given sentence.
    

    如果您要检查多个匹配项,那么使用enumerate 进行列表理解是可行的方法:

    r = [i for i, j in enumerate(words, start=1) if j == askedword]
    

    然后检查列表是否为空并相应打印:

    if r:
        print("Positions of word:", *r)
    else:
        print("Word is not in the given sentence.")
    

    【讨论】:

    • 这只会定位句子中第一次出现的单词,例如如果我输入句子dog sat on the dog,它应该拿出1和5,有没有我可以做到这一点?
    • @Dummy8123 对,显然你没有一个答案想检查是否多次出现,我更新了我的答案来解决这个问题。
    【解决方案2】:

    Jim 的回答——结合对 askedword in words 的测试和对 words.index(askedword) 的调用——在我看来是最好的和最 Pythonic 的方法。

    相同方法的另一个变体是使用try-except

    try:
        print(words.index(askedword) + 1) 
    except ValueError:
        print("word not in sentence")
    

    但是,我只是想指出,OP 代码的结构看起来您可能一直在尝试采用以下模式,这也有效:

    for i, word in enumerate(words):
        if askedword == word :
            print(i+1)
            break
    else:    # triggered if the loop runs out without breaking
        print ("word not in sentence")
    

    在大多数其他编程语言中没有的不寻常的转折中,这个else 绑定到for 循环,而不是if 语句(没错,让你的编辑从我的缩进中解放出来)。 See the python.org documentation here.

    【讨论】:

    • 我试过了,除了一个,但它似乎只输出了第一个位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多