trans_methods.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2024/5/16
  3. # @Author : 魏志亮
  4. import ast
  5. import datetime
  6. import os
  7. import shutil
  8. import warnings
  9. import chardet
  10. import pandas as pd
  11. from utils.log.import_data_log import log_print
  12. warnings.filterwarnings("ignore")
  13. # 获取文件编码
  14. def detect_file_encoding(filename):
  15. # 读取文件的前1000个字节(足够用于大多数编码检测)
  16. with open(filename, 'rb') as f:
  17. rawdata = f.read(1000)
  18. result = chardet.detect(rawdata)
  19. encoding = result['encoding']
  20. log_print("文件类型:", filename, encoding)
  21. if encoding is None:
  22. encoding = 'gb18030'
  23. if encoding.lower() in ['utf-8', 'ascii', 'utf8', 'utf-8-sig']:
  24. return 'utf-8'
  25. return 'gb18030'
  26. def del_blank(df=pd.DataFrame(), cols=list()):
  27. for col in cols:
  28. if df[col].dtype == object:
  29. df[col] = df[col].str.strip()
  30. return df
  31. # 切割数组到多个数组
  32. def split_array(array, num):
  33. return [array[i:i + num] for i in range(0, len(array), num)]
  34. def find_header(file_path, use_cols=list()):
  35. df = read_file_to_df(file_path, None, None, 50)
  36. count = 0
  37. header = None
  38. for index, row in df.iterrows():
  39. values = row.values
  40. for col in use_cols:
  41. if col in values:
  42. count = count + 1
  43. if count > 2:
  44. header = index
  45. break
  46. return header
  47. # 读取数据到df
  48. def read_file_to_df(file_path, use_cols=None, header=None, nrows=None):
  49. begin = datetime.datetime.now()
  50. log_print('开始读取文件', file_path)
  51. base_name = os.path.basename(file_path)
  52. df = pd.DataFrame()
  53. try:
  54. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  55. encoding = detect_file_encoding(file_path)
  56. end_with_gz = str(file_path).lower().endswith("gz")
  57. if end_with_gz:
  58. df = pd.read_csv(file_path, encoding=encoding, usecols=use_cols, compression='gzip',
  59. header=header, nrows=nrows)
  60. else:
  61. df = pd.read_csv(file_path, encoding=encoding, usecols=use_cols, header=header,
  62. on_bad_lines='warn', nrows=nrows)
  63. else:
  64. xls = pd.ExcelFile(file_path)
  65. # 获取所有的sheet名称
  66. sheet_names = xls.sheet_names
  67. for sheet_name in sheet_names:
  68. if use_cols:
  69. now_df = pd.read_excel(xls, sheet_name=sheet_name, header=header, usecols=use_cols, nrows=nrows)
  70. else:
  71. now_df = pd.read_excel(xls, sheet_name=sheet_name, header=header, nrows=nrows)
  72. now_df['sheet_name'] = sheet_name
  73. df = pd.concat([df, now_df])
  74. xls.close()
  75. df['file_name'] = base_name[:str(base_name).rfind(".")]
  76. log_print('文件读取成功:', file_path, '数据数量:', df.shape, '耗时:', datetime.datetime.now() - begin)
  77. except Exception as e:
  78. log_print('读取文件出错', file_path, str(e))
  79. message = '文件:' + os.path.basename(file_path) + ',' + str(e)
  80. raise ValueError(message)
  81. return df
  82. def __build_directory_dict(directory_dict, path, filter_types=None):
  83. # 遍历目录下的所有项
  84. for item in os.listdir(path):
  85. item_path = os.path.join(path, item)
  86. if os.path.isdir(item_path):
  87. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  88. elif os.path.isfile(item_path):
  89. if path not in directory_dict:
  90. directory_dict[path] = []
  91. if filter_types is None or len(filter_types) == 0:
  92. directory_dict[path].append(item_path)
  93. elif str(item_path).split(".")[-1] in filter_types:
  94. if str(item_path).count("~$") == 0:
  95. directory_dict[path].append(item_path)
  96. # 读取路径下所有的excel文件
  97. def read_excel_files(read_path, filter_types=None):
  98. if filter_types is None:
  99. filter_types = ['xls', 'xlsx', 'csv', 'gz']
  100. if os.path.isfile(read_path):
  101. return [read_path]
  102. directory_dict = {}
  103. __build_directory_dict(directory_dict, read_path, filter_types=filter_types)
  104. return [path for paths in directory_dict.values() for path in paths if path]
  105. # 读取路径下所有的文件
  106. def read_files(read_path, filter_types=None):
  107. if filter_types is None:
  108. filter_types = ['xls', 'xlsx', 'csv', 'gz', 'zip', 'rar']
  109. if os.path.isfile(read_path):
  110. return [read_path]
  111. directory_dict = {}
  112. __build_directory_dict(directory_dict, read_path, filter_types=filter_types)
  113. return [path1 for paths in directory_dict.values() for path1 in paths if path1]
  114. def copy_to_new(from_path, to_path):
  115. is_file = False
  116. if to_path.count('.') > 0:
  117. is_file = True
  118. create_file_path(to_path, is_file_path=is_file)
  119. shutil.copy(from_path, to_path)
  120. # 创建路径
  121. def create_file_path(read_path, is_file_path=False):
  122. """
  123. 创建路径
  124. :param read_path:创建文件夹的路径
  125. :param is_file_path: 传入的path是否包含具体的文件名
  126. """
  127. if is_file_path:
  128. read_path = os.path.dirname(read_path)
  129. if not os.path.exists(read_path):
  130. os.makedirs(read_path, exist_ok=True)
  131. def valid_eval(eval_str):
  132. """
  133. 验证 eval 是否包含非法的参数
  134. """
  135. safe_param = ["column", "wind_name", "df", "error_time", "str", "int"]
  136. eval_str_names = [node.id for node in ast.walk(ast.parse(eval_str)) if isinstance(node, ast.Name)]
  137. if not set(eval_str_names).issubset(safe_param):
  138. raise NameError(
  139. eval_str + " contains unsafe name :" + str(','.join(list(set(eval_str_names) - set(safe_param)))))
  140. return True
  141. if __name__ == '__main__':
  142. # aa = valid_eval("column[column.find('_')+1:]")
  143. # print(aa)
  144. #
  145. # aa = valid_eval("df['123'].apply(lambda wind_name: wind_name.replace('元宝山','').replace('号风机',''))")
  146. # print(aa)
  147. #
  148. # aa = valid_eval("'记录时间' if column == '时间' else column;from os import *; path")
  149. # print(aa)
  150. df = read_file_to_df(r"D:\data\11-12月.xls",
  151. trans_cols=['风机', '时间', '有功功率', '无功功率', '功率因数', '频率'], nrows=30)
  152. print(df.columns)