Created
January 3, 2013 17:28
-
-
Save mohd-akram/4445152 to your computer and use it in GitHub Desktop.
An intuitive method to sort results in a few lines (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""This module sorts a list of results based on a query. | |
If there is an intersection between words in the query and a result, it | |
is placed near the beginning of the list (based on length of intersection). | |
If there is no intersection, the position of the query (substring) in the | |
result (string) is used for sorting. These results are placed toward the end | |
of the list. | |
""" | |
import re | |
def split(string): | |
"""Splits a string at special characters including whitespace""" | |
return [i for i in re.split(r'\W+', string.lower()) if i] | |
def sort(query, results): | |
"""Sort a list of results based on a query""" | |
querylist = split(query) | |
key = lambda k: (len(set(querylist).intersection(split(k))) | |
or -k.lower().find(query.lower())) | |
return sorted(results, key=key, reverse=True) | |
query = 'box' | |
items = ['box', 'candy box', 'boxy', 'Xbox', 'Dropbox', 'B-box', 'suboxide'] | |
print(sort(query, items)) | |
# Result | |
# ['box', 'candy box', 'B-box', 'boxy', 'Xbox', 'suboxide', 'Dropbox'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment