Im trying to check how much does the query matches the search
Here is the full code:
import tempfile
from whoosh import index
from whoosh.fields import Schema, TEXT, ID
from whoosh.qparser import QueryParser
def most_similar_key(string, dictionary):
"""Finds the most similar key to the given string in the given dictionary."""
most_similar_key = None
global most_similar_score
most_similar_score = 0
schema = Schema(key=ID(stored=True), text=TEXT(stored=True))
# Create an in-memory directory for the index
with tempfile.TemporaryDirectory() as temp_dir:
ix = index.create_in(temp_dir, schema)
with ix.writer() as writer:
for key in dictionary:
writer.add_document(key=key, text=dictionary[key])
with ix.searcher() as searcher:
query_parser = QueryParser("text", schema=schema)
query = query_parser.parse(string)
results = searcher.search(query)
if len(results) > 0:
most_similar_key = results[0]['key']
most_similar_score = results[0].score
return most_similar_key, most_similar_score
def print_value_to_key(string, dictionary):
"""Prints the value to the key that is most similar to the given string."""
key, score = most_similar_key(string, dictionary)
if key is not None:
value = dictionary[key]
similarity_percentage = score * 100
print(f"{key}: {value} ({similarity_percentage:.2f}%)")
else:
print("No similar key found.")
if __name__ == "__main__":
dictionary = {
'go to playstore, download a game, find it on home screen, click on it and start playing' : 'how to play games',
'in the sea' : 'where are the fish',
'its yellow' : 'what is the color of the sun'
}
string = "how to play games"
print_value_to_key(string, dictionary)
The problem is that the score is above 1 so when it gets multiplied by 100 it gives off percentage Im new to Whoosh so i dont know what to do
Ive actually not really tried anything since I dont really understand the code