English 中文(简体)
如何在Python中检查句子是否包含某个单词,然后执行操作?
原标题:How do I check if a sentence contains a certain word in Python and then perform an action?
  • 时间:2010-10-09 21:31:03
  •  标签:
  • python
  • input

比方说,我向用户询问原始输入,他们说:“这是一条消息。”如果原始输入包含“消息”一词,它会在那之后执行一个操作。我能看看怎么做吗?

最佳回答

根据@kniti的评论,问题是你需要先把句子分成单词,然后检查:

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()

否则,如果你有一句“That one is a classic”,并且你试图检查它是否包含“lass”一词,它会错误地返回True。

当然,这仍然不是完美的,因为你可能需要担心去掉标点符号之类的事情,否则“That one is a classic”这句话在搜索“classic”时仍然会返回False(因为结尾的句号)。这里有一篇关于从Python句子中去除标点符号的好文章,而不是重新发明轮子:

从字符串中去除标点符号的最佳方式

还需要考虑区分大小写,因此在进行搜索之前,您可能需要将raw_input结果和搜索词更改为小写。只需在str类上使用lower()函数,就可以很容易地做到这一点。

这些问题看起来总是那么简单。。。

问题回答

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

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语句的方法。

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

只需写:

term = what you want to be checked in input or something y = input function # what you want to be inputted note: taking y as input is not necessary You can take whatever you want!

然后写

如果y中的词条:#检查y(输入)是否包含要检查的单词

what you want to do

看就这么简单

if "message" in sentence:
    do_action()




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签