Skip to content

Instantly share code, notes, and snippets.

@sirodoht
Last active November 14, 2018 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirodoht/f48d20a9525b3b6c12177ed20a9bc166 to your computer and use it in GitHub Desktop.
Save sirodoht/f48d20a9525b3b6c12177ed20a9bc166 to your computer and use it in GitHub Desktop.
Slugify CLI tool in Python
#!/usr/bin/env python3
# Usage:
# slugify any thing here really
# Stolen from Django:
# https://github.com/django/django/blob/277017aea4cf72a1797102e6d129165181d04e17/django/utils/text.py#L386
import re
import sys
import unicodedata
def slugify(value):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
"""
value = str(value)
value = (
unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode("ascii")
)
value = re.sub(r"[^\w\s-]", "", value).strip().lower()
return re.sub(r"[-\s]+", "-", value)
def main():
if len(sys.argv) == 1:
print("Usage: slugify any thing here really")
exit(0)
cli_arguments = str(sys.argv[1:])
print(slugify(cli_arguments))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment