Created
September 27, 2016 18:44
-
-
Save cwardzala/8a8b43841da73f19a44d9a598a601035 to your computer and use it in GitHub Desktop.
null created by anonymous - https://repl.it/X3G/4601
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
#/usr/bin/env python | |
import re | |
import json | |
def slugify(title): | |
title = title.lower() | |
empties = re.compile('[-\\s]+') | |
title = empties.sub('-', title) | |
odds = re.compile('[^\w\s-]') | |
title = odds.sub('', title) | |
return title | |
v = [ | |
{'title': 'Apartment, The'}, | |
{'title': 'Bar'}, | |
{'title': 'Apartment, The'}, | |
{'title': 'Foo'}, | |
{'title': 'Foo'}, | |
{'title': 'The Foo is Strong'}, | |
{'title': 'Foo Bar'}, | |
{'title': 'Foo: 3'} | |
] | |
ov = [] | |
for item in v: | |
# make a base slug of the title | |
slug = slugify(item['title']) | |
# create regex with base slug | |
reg = ur"^" + slug + "(-[0-9][^a-z]*)?$" | |
print reg | |
# find all items already loaded that have same slug with or without "-n" | |
matches = [a for a in ov if re.match(reg, slugify(a['title']), re.MULTILINE)] | |
if len(matches) > 0: | |
# if we have some matching slugs add "-n" with the next index | |
item['slug'] = "%s-%i" % (slug, len(matches)) | |
else: | |
# if no matches then just use the base slug | |
item['slug'] = slug | |
ov.append(item) | |
print json.dumps(ov, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment