def url_name_suggestions(request): # there's a 'name' in request: # take it and return a list of a few company url suggestions suggestions = [] try: # get name from sent data name = JsonParse(request.POST.get('data'))['name'] except: return JsonResponse({'suggestions':[]}) # 0. "lowercaseize" name = name.lower() # 1. "asciify" s = unidecode.unidecode(name) # 2. remove forbidden characters (everything but alphanumeric and dash) ("alphanumerify") s = re.sub(r'[^\w-]', ' ', s).strip() # first suggestion: full name - also remove duplicate -'s suggestions.append(unique_url_name(re.sub(r' +', '-', s))) # 2. remove one-character words ("unonecharacterify") # regex: one character followed by a space at the beginning OR # space followed by a character followed by a space OR # space followed by a character at the end s = re.sub(r'(^. )|(( ).(?= ))|( .$)', ' ', s) # 3. suggestions: # first word, then first and second, then ..., up to g.MISC['company_url_length'] chars max_len = g.MISC['company_url_length'] words = s.split() for w in range(1, len(words)+1): s = '' for i in range(w): s += '-' + words[i] s = s[1:] # cut off the first '-' if len(s) >= max_len: break suggestions.append(unique_url_name(s)) # only first characters of every word (a.k.a. acronym) s = '' for w in words: s += w[0] suggestions.append(unique_url_name(s)) # 4. remove possible inapropriate suggestions valid = [] for s in suggestions: if check_url_name(s): valid.append(s) # 5. remove duplicates valid = list(set(valid)) # 6. sort by length valid.sort(key=len) suggestions = valid del valid # 3a. add a random string to suggestions suggestions.append(unique_url_name(get_random_string(length=5).lower())) # pass on to the page return JsonResponse({'suggestions':suggestions})