如何在Python中检查句子是否包含某个单词并执行操作?

12 投票
5 回答
93496 浏览
提问于 2025-04-16 05:15

假设我让用户输入一些内容,他们说了:“这是一条消息。”如果这个输入里包含了“消息”这个词,那么程序就会在之后执行某个操作。我想知道这可以怎么实现?

5 个回答

1
def findDog(st):
    return 'dog' in st.lower().split()
findDog('Is there a dog here?')

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

3

这当然是一个非常简单的例子:

if "message" in raw_input():
    action()

如果你需要把不同的词映射到不同的动作上,你可以这样做:

# actions
def action():
    print "action"

def other_action():
    print "other action"

def default_action():
    print "default action"

# word to action translation function
def word_to_action(word):
    return {
        "message":  action,
        "sentence": other_action
    }.get(word, default_action)()

# get input, split into single words
w = raw_input("Input: ").split()

# apply the word to action translation to every word and act accordingly
map(word_to_action, w)

注意,这里还定义了一个默认的动作,用于处理输入中没有任何触发词的情况。

想了解更多关于上面这种映射方式的细节,可以查看 这里,这实际上是Python实现“switch语句”的一种方式。

16

根据@knitti的评论,问题在于你需要先把句子拆分成单词,然后再进行检查:

term = "message" #term we want to search for
input = raw_input() #read input from user

words = input.split() #split the sentence into individual words

if term in words: #see if one of the words in the sentence is the word we want
    do_stuff()

否则,如果你有句子“那句是经典”,然后你想检查里面是否有“lass”这个词,它会错误地返回True。

当然,这样做也不完美,因为你还得考虑去掉标点符号,比如逗号、句号等等。否则,句子“那句是经典。”在搜索“经典”时会返回False,因为句子末尾有个句号。与其重新发明轮子,这里有一篇关于如何在Python中去掉句子标点符号的好文章:

在字符串中去掉标点符号的最佳方法

你还得考虑大小写的问题,所以在搜索之前,你可能想把raw_input的结果和你的搜索词都转换成小写。你可以很简单地通过在str类上使用lower()函数来做到这一点。

这些问题总是看起来很简单……

撰写回答