trans_methods.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2024/5/16
  3. # @Author : 魏志亮
  4. import os
  5. import re
  6. import shutil
  7. import warnings
  8. import chardet
  9. import pandas as pd
  10. from utils.log.trans_log import trans_print
  11. warnings.filterwarnings("ignore")
  12. # 获取文件编码
  13. def detect_file_encoding(filename):
  14. # 读取文件的前1000个字节(足够用于大多数编码检测)
  15. with open(filename, 'rb') as f:
  16. rawdata = f.read(1000)
  17. result = chardet.detect(rawdata)
  18. encoding = result['encoding']
  19. trans_print("文件类型:", filename, encoding)
  20. if encoding is None:
  21. encoding = 'gb18030'
  22. if encoding and encoding.lower() == 'gb2312' or encoding.lower().startswith("windows"):
  23. encoding = 'gb18030'
  24. return encoding
  25. def del_blank(df=pd.DataFrame(), cols=list()):
  26. for col in cols:
  27. if df[col].dtype == object:
  28. df[col] = df[col].str.strip()
  29. return df
  30. # 读取数据到df
  31. def read_file_to_df(file_path, read_cols=list()):
  32. trans_print('开始读取文件', file_path)
  33. df = pd.DataFrame()
  34. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  35. encoding = detect_file_encoding(file_path)
  36. end_with_gz = str(file_path).lower().endswith("gz")
  37. if read_cols:
  38. if end_with_gz:
  39. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip')
  40. else:
  41. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols)
  42. else:
  43. if end_with_gz:
  44. df = pd.read_csv(file_path, encoding=encoding, compression='gzip')
  45. else:
  46. df = pd.read_csv(file_path, encoding=encoding)
  47. else:
  48. xls = pd.ExcelFile(file_path)
  49. # 获取所有的sheet名称
  50. sheet_names = xls.sheet_names
  51. for sheet in sheet_names:
  52. if read_cols:
  53. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, usecols=read_cols)])
  54. else:
  55. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet)])
  56. trans_print('文件读取成功', file_path, '文件数量', df.shape)
  57. return df
  58. def __build_directory_dict(directory_dict, path, filter_types=None):
  59. # 遍历目录下的所有项
  60. for item in os.listdir(path):
  61. item_path = os.path.join(path, item)
  62. if os.path.isdir(item_path):
  63. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  64. elif os.path.isfile(item_path):
  65. if path not in directory_dict:
  66. directory_dict[path] = []
  67. if filter_types is None or len(filter_types) == 0:
  68. directory_dict[path].append(item_path)
  69. elif str(item_path).split(".")[-1] in filter_types:
  70. if str(item_path).count("~$") == 0:
  71. directory_dict[path].append(item_path)
  72. # 读取所有文件
  73. # 读取路径下所有的excel文件
  74. def read_excel_files(read_path):
  75. directory_dict = {}
  76. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  77. return [path for paths in directory_dict.values() for path in paths if path]
  78. # 读取路径下所有的文件
  79. def read_files(read_path):
  80. directory_dict = {}
  81. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz', 'zip', 'rar'])
  82. return [path for paths in directory_dict.values() for path in paths if path]
  83. def copy_to_new(from_path, to_path):
  84. is_file = False
  85. if to_path.count('.') > 0:
  86. is_file = True
  87. create_file_path(to_path, is_file_path=is_file)
  88. shutil.copy(from_path, to_path)
  89. # 创建路径
  90. def create_file_path(path, is_file_path=False):
  91. if is_file_path:
  92. path = os.path.dirname(path)
  93. if not os.path.exists(path):
  94. os.makedirs(path, exist_ok=True)
  95. # 格式化风机名称
  96. def generate_turbine_name(turbine_name='F0001', prefix='F'):
  97. strinfo = re.compile(r"[\D*]")
  98. name = strinfo.sub('', str(turbine_name))
  99. return prefix + str(int(name)).zfill(3)