Python在字符串中搜索某些关键字

时间:2017-11-04 03:46:16

标签: python

现在我有一个单独的关键词列表是否有办法将其组合成一个数组或字符串并搜索单个单词而不必分离每个关键字并使其可重复?

keywordlist = ("pricing")
keywordlist1 = ("careers")
keywordlist2 = ("quotes")
keywordlist3 = ("telephone number")
keywordlist5 = ("about")
while True:
    question1 = raw_input("Is there anything I can help with today?   ")
    question_parts = question1.split(" ")
    for word in question_parts:
        if word.lower() in keywordlist:
            print("Yah i can show you some pricing:   ")
        elif word.lower() in keywordlist1:
            print("Here is our career page and feel free to apply:  ")
        elif word.lower() in keywordlist2:
            print("yah i can show you to our quote page: ")
        elif word.lower() in keywordlist3:
            print("Yah here is our contact page and feel free to contact us: ")
        elif word.lower() in keywordlist5:
            print("Here is some information about us:")
        goagain = raw_input("Would you like any More Help? (Yes/No)")
        if goagain == "Yes":
            #Get values again
            pass #or do whatever
        elif goagain != "Yes":
            print ("Bye!")
    break

2 个答案:

答案 0 :(得分:3)

您可以使用dictionary

keywords = {"pricing": "Yah i can show you some pricing:   "
            "careers": "Here is our career page and feel free to apply:  "
            "quotes": "yah i can show you to our quote page: "
            "telephone": "Yah here is our contact page and feel free to contact us: "
            "about": "Here is some information about us:"}
while True:
    question1 = raw_input("Is there anything I can help with today?   ")
    question_parts = question1.lower().split()
    for word in question_parts:
        if word in keywords:
            print(keywords[word])
    goagain = raw_input("Would you like any More Help? (Yes/No)")
    if goagain == "Yes":
        #Get values again
    else:
        print ("Bye!")
        break

答案 1 :(得分:0)

使用正则表达式

import re 
KEYWORD_MAPPING = {
        "pricing": "Yah i can show you some pricing:",
        "careers": "Here is our career page and feel free to apply:",
        "quotes": "yah i can show you to our quote page:",
        "telephone": "Yah here is our contact page and feel free to contact us: ",
        "about": "Here is some information about us:"
}

def search_for_keyword(question):
    keyword_pattern = r'{}'.format('|'.join(KEYWORD_MAPPING.keys()))
    keyword = re.search(keyword_pattern, question, re.I).group()
    if not keyword:
         return False
    print(KEYWORD_MAPPING[keyword])
    return True

while True:
        question = input('enter a question')
        status = search_for_keyword(question)
        if not status:
             break