-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
72 lines (60 loc) · 2 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
# -*- coding: utf-8 -*-
"""
@project: custom words similarity
@author: David
@time: 2021/8/20 15:13
"""
import re
import os
import json
import numpy as np
class Utils(object):
def __init__(self):
pass
#问题:静态方法在内存中的类是单例的吗?
@staticmethod
def fetch_chinese(word):
pattern = re.compile(r'[^\u4e00-\u9fa5]')
chinese = re.sub(pattern, '', word)
return chinese
@staticmethod
def write(data, fileName):
dir_path = os.path.dirname(os.path.realpath(__file__))
# 获取excel所在文件目录
result = os.path.join(dir_path, 'data', fileName)
with open(r'{}'.format(result), 'w', encoding='utf-8') as f:
qd = json.dumps(data, ensure_ascii=False) # Json序列化
f.write(qd)
f.close()
@staticmethod
def read(fileName):
dir_path = os.path.dirname(os.path.realpath(__file__))
# 获取excel所在文件目录
path = os.path.join(dir_path, '语料', fileName)
with open(path, 'r', encoding='utf-8') as load_f:
result = json.load(load_f)
return result
dir_path = os.path.dirname(os.path.realpath(__file__))
def writeEmb(path, datas):
with open(r'{}'.format(path), 'w', encoding='utf-8') as f:
for key, value in datas.items():
new_value = map(lambda x:str(x), value)
f.write(key+'\t'+",".join(new_value)+'\n')
f.close()
def writeStr(path, strs):
with open(r'{}'.format(path), 'w', encoding='utf-8') as f:
f.write(strs)
f.close()
def writeJson(path, data):
with open(r'{}'.format(path), 'w', encoding='utf-8') as f:
qd = json.dumps(data, ensure_ascii=False) # Json序列化
f.write(qd)
f.close()
def readLines(path):
with open(path, encoding='utf-8') as f:
result = f.readlines()
return result
def readDict(path):
with open(path, 'r', encoding='utf-8') as load_f:
result = json.load(load_f)
return result