- Author:
- henriklied
- Posted:
- June 15, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 4 (after 4 ratings)
This function looks up items similar to a specific string. Requires the Levenshtein module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from Levenshtein import ratio
from django.contrib.contenttypes.models import ContentType
def get_similar_items(mod, field, string, similarity_ratio=0.6, limit=None):
"""
Get similar items for a specific model
Example usage:
similar = get_similar_items(Entry, 'title', 'Espresso is good for you', 0.5, 10)
var = Entry.objects.filter(id__in=similar)
"""
similar_list_id = []
v = ContentType.objects.get_for_model(mod)
c = v.model_class()
for i in c.objects.all():
if ratio(string, getattr(i,field)) > similarity_ratio:
similar_list_id.append(i.id)
return similar_list_id[:limit]
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.