Fundraising in PDF.
[wolnelektury.git] / src / sortify.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import re
5 from fnpdjango.utils.text import char_map
6
7
8 # Specifies diacritics order.
9 # Default order is zero, max is 9
10 char_order = {
11     'ż': 1, 'Ż': 1,
12 }
13
14
15 def replace_char(m):
16     char = m.group()
17     if char in char_map:
18         order = char_order.get(char, 0)
19         return "%s~%d" % (char_map[char], order)
20     else:
21         return char
22
23
24 def sortify(value):
25     """
26         Turns Unicode into ASCII-sortable str
27
28         Examples :
29
30         >>> sortify('a a') < sortify('aa') < sortify('ą') < sortify('b')
31         True
32
33         >>> sortify('ź') < sortify('ż')
34         True
35
36     """
37
38     if not isinstance(value, str):
39         value = str(value, 'utf-8')
40
41     # try to replace chars
42     value = re.sub('[^a-zA-Z0-9\\s\\-]', replace_char, value)
43     value = value.lower()
44     value = re.sub(r'[^a-z0-9~]+', ' ', value)
45     
46     return value.encode('ascii', 'ignore').decode('ascii')