utils.py 1017 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import random
  2. import string
  3. import urllib.parse
  4. from unidecode import unidecode
  5. from .config import WORDS_FILE_PATH
  6. from .log import LOG
  7. with open(WORDS_FILE_PATH) as f:
  8. LOG.d("load words file: %s", WORDS_FILE_PATH)
  9. _words = f.read().split()
  10. def random_word():
  11. return random.choice(_words)
  12. def word_exist(word):
  13. return word in _words
  14. def random_words():
  15. """Generate a random words. Used to generate user-facing string, for ex email addresses"""
  16. nb_words = random.randint(2, 3)
  17. return "_".join([random.choice(_words) for i in range(nb_words)])
  18. def random_string(length=10):
  19. """Generate a random string of fixed length """
  20. letters = string.ascii_lowercase
  21. return "".join(random.choice(letters) for _ in range(length))
  22. def convert_to_id(s: str):
  23. """convert a string to id-like: remove space, remove special accent"""
  24. s = s.replace(" ", "")
  25. s = s.lower()
  26. s = unidecode(s)
  27. return s
  28. def encode_url(url):
  29. return urllib.parse.quote(url, safe="")