trans_methods.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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.trans_log import trans_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. trans_print("文件类型:", filename, encoding)
  21. if encoding is None:
  22. encoding = 'gb18030'
  23. if encoding.lower() in ['utf-8', 'ascii', 'utf8']:
  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_read_header(file_path, trans_cols):
  35. df = read_file_to_df(file_path, nrows=20)
  36. df.reset_index(inplace=True)
  37. count = 0
  38. header = None
  39. for col in trans_cols:
  40. if col in df.columns:
  41. count = count + 1
  42. if count >= 2:
  43. header = 0
  44. break
  45. count = 0
  46. values = list()
  47. for index, row in df.iterrows():
  48. for col in trans_cols:
  49. if col in row.values:
  50. count = count + 1
  51. if count > 2:
  52. header = index + 1
  53. break
  54. read_cols = []
  55. for col in values:
  56. if col in trans_cols:
  57. read_cols.append(col)
  58. return header, read_cols
  59. # 读取数据到df
  60. def read_file_to_df(file_path, read_cols=list(), trans_cols=None, nrows=None, not_find_header='raise'):
  61. begin = datetime.datetime.now()
  62. trans_print('开始读取文件', file_path)
  63. header = 0
  64. find_cols = list()
  65. if trans_cols:
  66. header, find_cols = find_read_header(file_path, trans_cols)
  67. trans_print(os.path.basename(file_path), "读取第", header, "行")
  68. if header is None:
  69. if not_find_header == 'raise':
  70. message = '未匹配到开始行,请检查并重新指定'
  71. trans_print(message)
  72. raise Exception(message)
  73. elif not_find_header == 'ignore':
  74. pass
  75. read_cols.extend(find_cols)
  76. df = pd.DataFrame()
  77. if header is not None:
  78. try:
  79. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  80. encoding = detect_file_encoding(file_path)
  81. end_with_gz = str(file_path).lower().endswith("gz")
  82. if read_cols:
  83. if end_with_gz:
  84. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip',
  85. header=header,
  86. nrows=nrows)
  87. else:
  88. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, header=header,
  89. on_bad_lines='warn', nrows=nrows)
  90. else:
  91. if end_with_gz:
  92. df = pd.read_csv(file_path, encoding=encoding, compression='gzip', header=header, nrows=nrows)
  93. else:
  94. df = pd.read_csv(file_path, encoding=encoding, header=header, on_bad_lines='warn', nrows=nrows)
  95. else:
  96. xls = pd.ExcelFile(file_path)
  97. # 获取所有的sheet名称
  98. sheet_names = xls.sheet_names
  99. for sheet_name in sheet_names:
  100. if read_cols:
  101. now_df = pd.read_excel(xls, sheet_name=sheet_name, header=header, usecols=read_cols,
  102. nrows=nrows)
  103. else:
  104. now_df = pd.read_excel(xls, sheet_name=sheet_name, header=header, nrows=nrows)
  105. now_df['sheet_name'] = sheet_name
  106. df = pd.concat([df, now_df])
  107. xls.close()
  108. trans_print('文件读取成功:', file_path, '数据数量:', df.shape, '耗时:', datetime.datetime.now() - begin)
  109. except Exception as e:
  110. trans_print('读取文件出错', file_path, str(e))
  111. message = '文件:' + os.path.basename(file_path) + ',' + str(e)
  112. raise ValueError(message)
  113. return df
  114. def __build_directory_dict(directory_dict, path, filter_types=None):
  115. # 遍历目录下的所有项
  116. for item in os.listdir(path):
  117. item_path = os.path.join(path, item)
  118. if os.path.isdir(item_path):
  119. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  120. elif os.path.isfile(item_path):
  121. if path not in directory_dict:
  122. directory_dict[path] = []
  123. if filter_types is None or len(filter_types) == 0:
  124. directory_dict[path].append(item_path)
  125. elif str(item_path).split(".")[-1] in filter_types:
  126. if str(item_path).count("~$") == 0:
  127. directory_dict[path].append(item_path)
  128. # 读取路径下所有的excel文件
  129. def read_excel_files(read_path):
  130. if os.path.isfile(read_path):
  131. return [read_path]
  132. directory_dict = {}
  133. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  134. return [path for paths in directory_dict.values() for path in paths if path]
  135. # 读取路径下所有的文件
  136. def read_files(read_path):
  137. if os.path.isfile(read_path):
  138. return [read_path]
  139. directory_dict = {}
  140. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz', 'zip', 'rar'])
  141. return [path for paths in directory_dict.values() for path in paths if path]
  142. def copy_to_new(from_path, to_path):
  143. is_file = False
  144. if to_path.count('.') > 0:
  145. is_file = True
  146. create_file_path(to_path, is_file_path=is_file)
  147. shutil.copy(from_path, to_path)
  148. # 创建路径
  149. def create_file_path(path, is_file_path=False):
  150. """
  151. 创建路径
  152. :param path:创建文件夹的路径
  153. :param is_file_path: 传入的path是否包含具体的文件名
  154. """
  155. if is_file_path:
  156. path = os.path.dirname(path)
  157. if not os.path.exists(path):
  158. os.makedirs(path, exist_ok=True)
  159. def valid_eval(eval_str):
  160. """
  161. 验证 eval 是否包含非法的参数
  162. """
  163. safe_param = ["column", "wind_name", "df", "error_time", "str", "int"]
  164. eval_str_names = [node.id for node in ast.walk(ast.parse(eval_str)) if isinstance(node, ast.Name)]
  165. if not set(eval_str_names).issubset(safe_param):
  166. raise NameError(
  167. eval_str + " contains unsafe name :" + str(','.join(list(set(eval_str_names) - set(safe_param)))))
  168. return True
  169. if __name__ == '__main__':
  170. # aa = valid_eval("column[column.find('_')+1:]")
  171. # print(aa)
  172. #
  173. # aa = valid_eval("df['123'].apply(lambda wind_name: wind_name.replace('元宝山','').replace('号风机',''))")
  174. # print(aa)
  175. #
  176. # aa = valid_eval("'记录时间' if column == '时间' else column;import os; os.path")
  177. # print(aa)
  178. df = read_file_to_df(r"D:\data\11-12月.xls", trans_cols=['风机', '时间', '有功功率', '无功功率', '功率因数', '频率'], nrows=30)
  179. print(df.columns)