图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.6 KiB

  1. from typing import Optional
  2. from ._util import to_string
  3. class Suggestion:
  4. """
  5. Represents a single suggestion being sent or returned from the
  6. autocomplete server
  7. """
  8. def __init__(
  9. self, string: str, score: float = 1.0, payload: Optional[str] = None
  10. ) -> None:
  11. self.string = to_string(string)
  12. self.payload = to_string(payload)
  13. self.score = score
  14. def __repr__(self) -> str:
  15. return self.string
  16. class SuggestionParser:
  17. """
  18. Internal class used to parse results from the `SUGGET` command.
  19. This needs to consume either 1, 2, or 3 values at a time from
  20. the return value depending on what objects were requested
  21. """
  22. def __init__(self, with_scores: bool, with_payloads: bool, ret) -> None:
  23. self.with_scores = with_scores
  24. self.with_payloads = with_payloads
  25. if with_scores and with_payloads:
  26. self.sugsize = 3
  27. self._scoreidx = 1
  28. self._payloadidx = 2
  29. elif with_scores:
  30. self.sugsize = 2
  31. self._scoreidx = 1
  32. elif with_payloads:
  33. self.sugsize = 2
  34. self._payloadidx = 1
  35. else:
  36. self.sugsize = 1
  37. self._scoreidx = -1
  38. self._sugs = ret
  39. def __iter__(self):
  40. for i in range(0, len(self._sugs), self.sugsize):
  41. ss = self._sugs[i]
  42. score = float(self._sugs[i + self._scoreidx]) if self.with_scores else 1.0
  43. payload = self._sugs[i + self._payloadidx] if self.with_payloads else None
  44. yield Suggestion(ss, score, payload)