使用术语和返回键搜索字典条件

时间:2016-07-13 21:01:47

标签: python dictionary

我有一个带有条件的字典,如果任何一个条款与条件匹配,我想要返回一个密钥。这是我的代码到目前为止的样子:

import re
import pyodbc

keyword_dictionary = {
    'Animals' : {'animal', 'dog', 'cat'},
    'Art' : {'art', 'sculpture', 'fearns','graphic','display','lights'},
    'Fruit' : {'yellow','fruit'},
}
def matcher(keywords, searcher):
    for word in searcher:
        for key, words in keywords.items():
            if word in words:
                result = []
                result.append(key)
                result1 = str(result).replace("['", "")
                final_result = str(result1).replace("']", "")
                print final_result

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=INSERT SERVER NAME;DATABASE=INSERT DATABASE NAME;UID=INSERT USERNAME;PWD=INSERT PASSWORD')
cursor = cnxn.cursor()

cursor.execute("SELECT TOP 50 [unique_id] \
      ,[terms] \
      ,[url] \ 
      FROM [INSERT DATABASE NAME].[dbo].[INSERT TABLE NAME]")

rows = cursor.fetchall()

for row in rows:
    terms = row[1]
matcher(keyword_dictionary, terms)

术语可能类似于

"wendy bought a dog" 

应打印密钥Animals

"that's a red fruit" 

应打印密钥Fruit

有谁知道如何编辑我的代码以便这样做?

4 个答案:

答案 0 :(得分:2)

设置操作是这里的方法:

body {
  padding-top: 70px;
}

答案 1 :(得分:1)

我不知道这段代码的pyodbc或游标部分是什么,但我尝试运行以下内容并且它有效。我不确定它是否正是你想要的,因为它在列表中返回答案而我可能会错过解释"术语的形式"输入

import re

keyword_dictionary = {
    'Animals' : {'animal', 'dog', 'cat'},
    'Art' : {'art', 'sculpture', 'fearns','graphic','display','lights'},
    'Fruit' : {'yellow','fruit'},
}
def matcher(keywords, terms):
    final_results = []
    for term in terms:
        for word in term.split(" "):
            for key, words in keywords.items():
                if word in words:
                    result = []
                    result.append(key)
                    result1 = str(result).replace("['", "")
                    final_results.append(str(result1).replace("']", ""))
    return final_results

terms = ["wendy bought a dog","that's a red fruit"]
results = matcher(keyword_dictionary, terms)
print results

得到以下特性:

['Animals', 'Fruit']

答案 2 :(得分:1)

您的代码将搜索者分成单个字母, 你需要按空格分割。 其余的似乎没问题。

示例:

searcher = 'wendy bought a dog'

# result: single letters
for word in searcher:
    print word

# result: words
for word in searcher.split(' '):
    print word

答案 3 :(得分:1)

我认为解决此问题的最简单方法是keyword_dictionary的{​​{3}}并对每个字词进行搜索。

我在reverse the keys and values上添加了一个简单的例子。

keyword_dictionary = {
    'Animals' : {'animal', 'dog', 'cat'},
    'Art' : {'art', 'sculpture', 'fearns','graphic','display','lights'},
    'Fruit' : {'yellow','fruit'},
}
#Swap the keys and values
keywords = dict(pair for key in keyword_dictionary.keys() for pair in dict.fromkeys(keyword_dictionary[key], key).items())

def keyword(sentence):
    for word in set(map(str.lower, sentence.split())):
        if word in keywords:
            return keywords[word]
    return None

print keyword("Wendy bought a dog")   #Returns "Animal"
print keyword("that's a red fruit")   #Returns "Fruit"