utils.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import re
  2. import string
  3. def clean_string(text):
  4. """
  5. This function takes in a string and performs a series of text cleaning operations.
  6. Args:
  7. text (str): The text to be cleaned. This is expected to be a string.
  8. Returns:
  9. cleaned_text (str): The cleaned text after all the cleaning operations
  10. have been performed.
  11. """
  12. # Replacement of newline characters:
  13. text = text.replace("\n", " ")
  14. # Stripping and reducing multiple spaces to single:
  15. cleaned_text = re.sub(r"\s+", " ", text.strip())
  16. # Removing backslashes:
  17. cleaned_text = cleaned_text.replace("\\", "")
  18. # Replacing hash characters:
  19. cleaned_text = cleaned_text.replace("#", " ")
  20. # Eliminating consecutive non-alphanumeric characters:
  21. # This regex identifies consecutive non-alphanumeric characters (i.e., not
  22. # a word character [a-zA-Z0-9_] and not a whitespace) in the string
  23. # and replaces each group of such characters with a single occurrence of
  24. # that character.
  25. # For example, "!!! hello !!!" would become "! hello !".
  26. cleaned_text = re.sub(r"([^\w\s])\1*", r"\1", cleaned_text)
  27. return cleaned_text
  28. def is_readable(s):
  29. """
  30. Heuristic to determine if a string is "readable" (mostly contains printable characters and forms meaningful words)
  31. :param s: string
  32. :return: True if the string is more than 95% printable.
  33. """
  34. printable_ratio = sum(c in string.printable for c in s) / len(s)
  35. return printable_ratio > 0.95 # 95% of characters are printable