Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Repository of scoring functions
- """
- import abc
- from typing import List
- class ScoringException(Exception):
- """ Generic exception raised by any scoring function."""
- pass
- class BaseScoringFunction(abc.ABC):
- """ API that any Scoring function should implement. """
- @abc.abstractmethod
- def score(self) -> float:
- """
- :return: Returns the score of the function.
- """
- pass
- class Term:
- """Sentence term"""
- def __init__(self, word: str, dictionary: str = 'RS'):
- self.word = word
- self.dictionary = dictionary
- class NLPScoringFunction(BaseScoringFunction):
- """ Scoring function that takes in a sentence and based on
- good/bad word classification assignees a score."""
- BAD_WORDS = ["slanina", "burger", "coca-cola"]
- GOOD_WORDS = ["spanac", "blitva", "celer", "avokado"]
- DICTIONARY = 'RS'
- def __init__(self, sentence: str):
- self._sentence = sentence
- def terms(self) -> List[Term]:
- return [Term(el) for el in self._sentence.split(" ")]
- def score(self) -> float:
- score = 1.0
- for term in self.terms():
- if term.dictionary != 'RS':
- raise ScoringException('Dictionary must be RS.')
- if term.word in self.BAD_WORDS:
- score = score * 1.5
- elif term.word in self.GOOD_WORDS:
- score = score * 0.5
- return score
- import unittest
- from unittest.mock import MagicMock
- from testing_example.scoring_functions import NLPScoringFunction, Term, \
- ScoringException, BaseScoringFunction
- def new_term():
- return [Term('rec', 'CN')]
- class TestNLPScoringFunction(unittest.TestCase):
- def test_positive_scores(self):
- scoring_function = NLPScoringFunction("Bolje spanac nego slanina")
- score = scoring_function.score()
- self.assertEquals(score, 0.75)
- assert score == 0.75
- def test_raises(self):
- scoring_function = NLPScoringFunction("Bolje spanac nego slanina")
- scoring_function.terms = new_term
- with self.assertRaises(ScoringException):
- scoring_function.score()
- # noinspection PyUnresolvedReferences
- def test_with_mock(self):
- scoring_function = NLPScoringFunction("")
- scoring_function.score = MagicMock()
- scoring_function.score.return_value = 0.75
- class Optimizer:
- def __init__(self, f: BaseScoringFunction):
- self.scoring_function = f
- def optimize(self):
- return self.scoring_function.score()
- o = Optimizer(scoring_function)
- o.optimize()
- scoring_function.score.assert_called()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement