搜索字符串

时间:2015-06-12 19:20:30

标签: python regex dictionary

我正在写一个小小的“测验”游戏作为练习。我将问题存储在字典中。我想要做的是能够提示搜索关键字,然后执行查找并打印所有键/值对,其中值包含与任何关键字匹配的字符串。

这是我用正则表达式和for循环处理的东西吗?我能够找到一些帖子,告诉我们如何根据确切的值找到键,但是我很难找到包含一个或多个关键字的值...

这是我到目前为止所拥有的:

questions = {'1':What is the capital of Zimbabwe?,'2':What is the State Flower of California?, '3':Honolulu is located in which state?}
searchterms = raw_input("Enter some keywords to search")
#### I get stuck here

更新: 忘记提到我使用pickle模块将我的问题字典存储在静态pkl文件中。

我正在使用以下代码加载问题词典:

def opendict():
    global questions
    pkl_file = open('questionslib.pkl', 'rb')
    questions = pickle.load(pkl_file)
    pkl_file.close()

3 个答案:

答案 0 :(得分:6)

使用字典上的iteritems()循环键值对,然后检查您的搜索是否在值中:

questions = {'1':'What is the capital of Africa?','2':'What is the State Flower of California?', '3':'Honolulu is located in which state?'}
searchterms = raw_input("Enter some keywords to search")

for k, v in questions.iteritems():
    if searchterms in v: print k, v

答案 1 :(得分:3)

您可以遍历字典并找到密钥,您可以将其存储在列表中或显示问题:

found = []
questions = {'1':What is the capital of Africa?,'2':What is the State Flower of California?, '3':Honolulu is located in which state?}
searchterms = raw_input("Enter some keywords to search")
for key, question in questions.iteritems():
    if len([x for x in search_terms.split() if question.find(x) > -1]):
        found.append(key)
        #print questions[key]

如果此人可以搜索更多的术语,您可以使用列表理解来查看匹配其中一个术语

PS:非洲不是一个国家:P

答案 2 :(得分:0)

您可以使用for循环和in运算符来满足您的要求,例如 -

def func(ques, keywords):
    res = []
    for k, q in ques.items():
        for keyword in keywords:
            if keyword in q.split(): # if you want to check whole words only,
                res.append((k,q))
    return res
questions = {'1':What is the capital of Africa?,'2':What is the State Flower of California?, '3':Honolulu is located in which state?}
searchterms = raw_input("Enter some keywords to search")
func(questions , keywords)