Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

56 строки
2.3 KiB

  1. import logging
  2. import string
  3. logger = logging.getLogger(__name__)
  4. def get_stopwords(path):
  5. logger.info("Attempting to load stopwords from file: '%s'", path)
  6. try:
  7. with open(path, 'r', encoding='utf-8-sig') as stopwords_file:
  8. logger.debug("Opened stopwords file '%s'", path)
  9. lines = stopwords_file.read().splitlines()
  10. stopwords = set(lines)
  11. logger.info("Successfully loaded %d unique stopwords from '%s' (%d total lines)", len(stopwords), path, len(lines))
  12. return stopwords
  13. except FileNotFoundError:
  14. logger.error("Stopwords file not found at path: '%s'", path, exc_info=True)
  15. raise
  16. except PermissionError:
  17. logger.error("Permission denied accessing stopwords file: '%s'", path, exc_info=True)
  18. raise
  19. except Exception as e:
  20. logger.error("Failed to load stopwords from '%s': %s", path, e, exc_info=True)
  21. raise
  22. def remove_stopwords(text, stopwords):
  23. logger.debug("Removing stopwords from text (%d chars): %r (available stopwords: %d)", len(text), text, len(stopwords))
  24. # split() without arguments handles all whitespace (spaces, tabs, newlines)
  25. words = text.split()
  26. sentence_words = []
  27. for word in words:
  28. # Strip surrounding punctuation and lowercase for comparison
  29. cleaned_word = word.strip(string.punctuation).lower()
  30. if cleaned_word and cleaned_word not in stopwords:
  31. sentence_words.append(word)
  32. elif cleaned_word in stopwords:
  33. logger.debug("Word filtered out as stopword: %r (original: %r)", cleaned_word, word)
  34. else:
  35. logger.debug("Word dropped (empty after stripping punctuation): %r", word)
  36. logger.debug("Filtered words: input=%d words, output=%d words -> %s", len(words), len(sentence_words), sentence_words)
  37. return sentence_words
  38. def normalize_headline(text, stopwords):
  39. logger.debug("Starting normalization of headline: %r", text)
  40. headline = text.strip().lower()
  41. punctuation = string.punctuation
  42. for char in punctuation:
  43. headline = headline.replace(char, '')
  44. logger.debug("Headline after lowercasing and punctuation removal: %r", headline)
  45. normalized = remove_stopwords(headline, stopwords)
  46. logger.debug("Completed normalization for %r -> %s", text, normalized)
  47. return normalized