magpces.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2018-09-06 14:21
  4. ---------
  5. @summary: 工具
  6. ---------
  7. @author: Boris
  8. @email: boris_liu@foxmail.com
  9. """
  10. import datetime
  11. import json
  12. import re
  13. from pprint import pformat
  14. print('sssssssss')
  15. _regexs = {}
  16. def get_info(html, regexs, allow_repeat=True, fetch_one=False, split=None):
  17. regexs = isinstance(regexs, str) and [regexs] or regexs
  18. infos = []
  19. for regex in regexs:
  20. if regex == "":
  21. continue
  22. if regex not in _regexs.keys():
  23. _regexs[regex] = re.compile(regex, re.S)
  24. if fetch_one:
  25. infos = _regexs[regex].search(html)
  26. if infos:
  27. infos = infos.groups()
  28. else:
  29. continue
  30. else:
  31. infos = _regexs[regex].findall(str(html))
  32. if len(infos) > 0:
  33. # print(regex)
  34. break
  35. if fetch_one:
  36. infos = infos if infos else ("",)
  37. return infos if len(infos) > 1 else infos[0]
  38. else:
  39. infos = allow_repeat and infos or sorted(set(infos), key=infos.index)
  40. infos = split.join(infos) if split else infos
  41. return infos
  42. def get_json(json_str):
  43. """
  44. @summary: 取json对象
  45. ---------
  46. @param json_str: json格式的字符串
  47. ---------
  48. @result: 返回json对象
  49. """
  50. try:
  51. return json.loads(json_str) if json_str else {}
  52. except Exception as e1:
  53. try:
  54. json_str = json_str.strip()
  55. json_str = json_str.replace("'", '"')
  56. keys = get_info(json_str, "(\w+):")
  57. for key in keys:
  58. json_str = json_str.replace(key, '"%s"' % key)
  59. return json.loads(json_str) if json_str else {}
  60. except Exception as e2:
  61. print(
  62. """
  63. e1: %s
  64. format json_str: %s
  65. e2: %s
  66. """
  67. % (e1, json_str, e2)
  68. )
  69. return {}
  70. def dumps_json(json_, indent=4, sort_keys=False):
  71. """
  72. @summary: 格式化json 用于打印
  73. ---------
  74. @param json_: json格式的字符串或json对象
  75. ---------
  76. @result: 格式化后的字符串
  77. """
  78. try:
  79. if isinstance(json_, str):
  80. json_ = get_json(json_)
  81. json_ = json.dumps(
  82. json_, ensure_ascii=False, indent=indent, skipkeys=True, sort_keys=sort_keys
  83. )
  84. except Exception as e:
  85. print(e)
  86. json_ = pformat(json_)
  87. return json_
  88. def get_current_date(date_format="%Y-%m-%d %H:%M:%S"):
  89. return datetime.datetime.now().strftime(date_format)
  90. # return time.strftime(date_format, time.localtime(time.time()))
  91. def key2hump(key):
  92. """
  93. 下划线试变成首字母大写
  94. """
  95. return key.title().replace("_", "")