-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquery_manager.py
51 lines (42 loc) · 2.08 KB
/
query_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from typing import Optional, List
def split_to_only_words_and_numbers(query: str) -> List: # removes special characters, only leaves words and numbers
filtered_words: List = []
word: str
for word in query.split(" "):
character: str
filtered_word: str = ""
for character in word.lower():
if character.isalpha() or character.isnumeric():
filtered_word += character
filtered_words.append(filtered_word)
return filtered_words
class QueryManager:
def __init__(self):
self.queries: List[QueryResponse] = []
def add_query(self, hot_words: List, minimum_number_of_hits: int, response: str) -> None:
self.queries.append(QueryResponse(hot_words, minimum_number_of_hits, response))
def get_best_response(self, query: str) -> Optional[str]:
query_words: List = split_to_only_words_and_numbers(query)
best_response_index: int = 0
best_response_hits = 0
for index, query_response in enumerate(self.queries):
current_query_hits = query_response.calculate_total_hits(query_words)
if current_query_hits > best_response_hits:
best_response_index = index
best_response_hits = current_query_hits
if best_response_hits == 0:
return None
return self.queries[best_response_index].response
class QueryResponse:
def __init__(self, hot_words: List, minimum_number_of_hits: int, response: str) -> None:
self.hot_words: List = hot_words # key words to look for
self.minimum_number_of_hits = minimum_number_of_hits # minimum number of word hits to deem a good response
self.response = response # automated response to send if deemed a good response
def calculate_total_hits(self, query_words: List) -> int:
hits = 0
for hot_word in self.hot_words:
if hot_word in query_words:
hits += 1
if hits < self.minimum_number_of_hits: # if does not have the minimum number of hits, ignore
return 0
return hits / len(self.hot_words)