get_clipboard_text_and_convert.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. # *****************************************************************************
  3. # Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
  4. # Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
  5. #
  6. # Distributed under the terms of the BSD License. The full license is in
  7. # the file COPYING, distributed as part of this software.
  8. # *****************************************************************************
  9. from typing import Any, List, Tuple
  10. from .api import get_clipboard_text
  11. def _make_num(x: Any) -> Any:
  12. try:
  13. return int(x)
  14. except ValueError:
  15. try:
  16. return float(x)
  17. except ValueError:
  18. try:
  19. return complex(x)
  20. except ValueError:
  21. return x
  22. def _make_list_of_list(txt: str) -> Tuple[
  23. List[List[Any]],
  24. bool,
  25. ]:
  26. ut = []
  27. flag = False
  28. for line in [x for x in txt.split("\r\n") if x != ""]:
  29. words = [_make_num(x) for x in line.split("\t")]
  30. if str in list(map(type, words)):
  31. flag = True
  32. ut.append(words)
  33. return (
  34. ut,
  35. flag,
  36. )
  37. def get_clipboard_text_and_convert(paste_list: bool = False) -> str:
  38. """Get txt from clipboard. if paste_list==True the convert tab separated
  39. data to list of lists. Enclose list of list in array() if all elements are
  40. numeric"""
  41. txt = get_clipboard_text()
  42. if not txt:
  43. return ""
  44. if not paste_list:
  45. return txt
  46. if "\t" not in txt:
  47. return txt
  48. array, flag = _make_list_of_list(txt)
  49. if flag:
  50. txt = repr(array)
  51. else:
  52. txt = "array(%s)" % repr(array)
  53. txt = "".join([c for c in txt if c not in " \t\r\n"])
  54. return txt