-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
275 lines (185 loc) · 4.77 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# -*- coding: utf-8 -*-
# @Time : 2018/7/31 10:09
# @Author : Allen
# @Site : 主要是读取文件(csv,txt),及pickle等
import os
import pickle
import re
import time
import uuid
import shutil
import jieba
import pandas as pd
from datetime import datetime
'''
获取当前项目路径
'''
def get_dir():
return os.path.dirname(os.getcwd()) + os.sep
'''
读取excel
'''
def load_excel(path, sheetname=False):
with open(path, 'rb') as f:
data = pd.read_excel(f, sheetname=sheetname)
return data
'''
读取csv
'''
def load_csv(path):
with open(path, 'r', encoding='gb18030') as f:
data = pd.read_csv(f)
return data
'''
判断目录
'''
def is_dir(path):
if not os.path.exists(path):
os.mkdir(path)
return True
else:
return True
'''
保存为pickle
'''
def save_pickle(path, maps):
with open(path, 'wb') as f:
pickle.dump(maps, f)
print("Success Save:%s" % (path))
'''
load pickle
'''
def load_pickle(path):
with open(path, 'rb') as f:
maps = pickle.load(f)
return maps
'''
保存数据
file_name:文件名
names:数据
flag:标注名
dir:目录名
'''
def save_format_data_csv(file_name, names, flag, file_dir):
dir_file = get_dir() + os.sep + file_dir + os.sep
if is_dir(dir_file):
file_name = dir_file + file_name
with open(file_name, 'a', encoding='utf8') as f:
for name in names:
f.write(name + "," + flag + "\n")
print("保存到: %s " % (file_name))
'''
保存数据csv
file_name:文件名
data:数据
file_dir:目录名
'''
def save_csv(file_name, df, file_dir):
dir_file = get_dir() + os.sep + file_dir + os.sep
if is_dir(dir_file):
file_name = dir_file + file_name
with open(file_name, 'w') as f:
df.to_csv(f, index=0)
print("保存到: %s " % (file_name))
'''
多功能替换
text:文本
dict:需要替换的内容
'''
def multiple_replace(text, dict):
regex = re.compile('|'.join(map(re.escape, dict)))
def one_xlat(match):
return dict[match.group(0)]
return regex.sub(one_xlat, text)
'''
保存为txt
'''
def save_txt(data, path):
with open(path, 'w', encoding='utf8') as f:
for d in data:
f.write(d + '\n')
print("Save Success !")
'''
判读文件是否存在
'''
def is_exists(path):
if os.path.exists(path):
return True
else:
return False
'''
判断是否为乱码
'''
def is_messy(sentence):
def new_len(iterable):
try:
return iterable.__len__()
except AttributeError:
return sum(1 for _ in iterable)
luanma_len = len(sentence)
luanma = jieba.cut(sentence)
res = float(luanma_len / new_len(luanma))
if res < 1.2:
return True
else:
return False
'''
是否为float
'''
def is_float(sentence):
try:
return type(eval(sentence)) == float
except:
return False
'''
读取txt
'''
def load_txt(path):
with open(path, 'r', encoding='utf-8') as f:
data = ([d.strip() for d in f.readlines()])
return data
'''
str to datetime
'''
def str_to_datetime(str):
return datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
'''
获取当前时间 datetime类型
'''
def get_datetime():
return datetime.strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S')
def get_uuid():
return str(uuid.uuid4()).replace('-', '')
'''
移动文件
'''
def move_file(source_path, total_path):
if is_dir(total_path):
try:
shutil.move(source_path, total_path)
except Exception as e:
try:
os.remove(source_path)
print(e)
print("移除已存在文件")
except:
pass
'''
把时间戳转化为时间: 1479264792 to 2016-11-16 10:53:12
'''
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return str_to_datetime(time.strftime('%Y-%m-%d %H:%M:%S', timeStruct))
'''
获取文件的创建时间
'''
def get_FileCreateTime(filePath):
t = os.path.getctime(filePath)
return TimeStampToTime(t)
'''获取文件的修改时间'''
def get_FileModifyTime(filePath):
t = os.path.getmtime(filePath)
return TimeStampToTime(t)
if __name__ == '__main__':
path = r'E:\san_wu\兴义地区各县局群资料.xlsx'
print(os.path.getsize(path) / 1024)