-
Notifications
You must be signed in to change notification settings - Fork 132
/
server.py.bak_d
executable file
·382 lines (325 loc) · 11.9 KB
/
server.py.bak_d
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/python3
import os
import sys
import time
import pickle
import pynlpir
from pynlpir import nlpir
from hanzi_util import is_zh_number,is_terminator,is_punct,is_zh,is_zhs
import hanzi_prep
import pinyin
import threading
import socket
import queue
# Server Side Configuration
HOST = "192.168.1.163"
PORT = 10244
FILE_NAME = "./data/jd.dat"
#分词处理
FILE_NAME_JIEBA_PK = FILE_NAME + "_JIEBA_PK"
FILE_NAME_JIEBA_PINYIN = FILE_NAME + "_JIEBA_PINYIN"
JIEBA_HZ = {}
if not os.path.exists(FILE_NAME_JIEBA_PK):
print("请计算产生词频数据!")
os.exit()
else:
print("加载JIEBA词频信息")
with open(FILE_NAME_JIEBA_PK, 'rb') as fin:
JIEBA_HZ = pickle.load(fin)
JIEBA_PINYIN = {}
if not os.path.exists(FILE_NAME_JIEBA_PINYIN):
print("请计算产生拼音信息!")
os.exit()
else:
print("加载JIEBA拼音信息")
with open(FILE_NAME_JIEBA_PINYIN, 'rb') as fin:
JIEBA_PINYIN = pickle.load(fin)
def sub_correct_me(pinyin, head, tail):
if not pinyin:
return None
if not head and not tail:
return None
def correct_me(str_test):
# str_len = len(str_test)
# print("\n==单字测试==")
# for i in range(1,str_len):
# tmp_str = str_test[i-1] + str_test[i]
# if is_terminator(str_test[i]):
# tmp_str = str_test[i-1] + '</s>'
# if is_terminator(str_test[i-1]):
# tmp_str = '<s>' + str_test[i]
# if UNIC_HZ.get(tmp_str):
# print("%s->%f" % (tmp_str,UNIC_HZ.get(tmp_str)),end="\t")
# else:
# print("%s->%f" % (tmp_str,0),end="\t")
print("")
print("==NLPIR分词==")
print("测试语句:%s" %(str_test))
line_p = hanzi_prep.split_into_sentences(str_test)
lines = []
for line_i in line_p:
lines.extend(line_i)
str_i = ''.join(lines)
#jieba_i = ' '.join(jieba.cut(str_i, cut_all=False))
print('准备进行分词')
jieba_i = ' '.join(pynlpir.segment(str_i, pos_tagging=False))
print("分词结果:%s"%(repr(jieba_i)))
jieba_i = jieba_i.split()
jieba_len = len(jieba_i)
if jieba_len < 3:
print("词数太小,放弃纠错!")
return
jieba_key = []
jieba_pro = []
for i in range(1,jieba_len):
#是否是标点符号
# if i == 0:
# tmp_str = '<s>' + jieba_i[i]
# if i == jieba_len -1:
# tmp_str = jieba_i[i] + '</s>'
# else:
# #默认模式
# tmp_str = jieba_i[i-1] + jieba_i[i]
# if len(jieba_i[i]) == 1:
# if is_terminator(jieba_i[i]):
# tmp_str = jieba_i[i-1] + '</s>'
# if len(jieba_i[i-1]) == 1:
# if is_terminator(jieba_i[i-1]):
# tmp_str = '<s>' + jieba_i[i]
#不考虑开头结尾模式
tmp_str = jieba_i[i-1] + jieba_i[i]
pro = JIEBA_HZ.get(tmp_str)
jieba_key.append(tmp_str)
if pro:
jieba_pro.append(pro)
else:
jieba_pro.append(0)
# if min_index != -1:
# print("\n可能错误位置:",end="")
# if min_index > 1:
# print("%s"%jieba_i[min_index-1],end="")
# print("%s"%jieba_i[min_index])
# if min_index < (jieba_len - 1):
# print("%s"%jieba_i[min_index+1],end="")
print("分词表:"+repr(jieba_key))
print("概率表:"+repr(jieba_pro))
jieba_pro_t = []
for i in range(0,jieba_len-2):
jieba_pro_t.append( jieba_pro[i] + jieba_pro[i+1])
min_index = jieba_pro_t.index(min(jieba_pro_t)) + 1
print("可疑位置:[%d]->%s"%(min_index,jieba_i[min_index]))
to_do = []
g_check_a = None
g_check_e = None
#纠错位置不可能在开头或者结尾
to_do.append(jieba_i[min_index-1])
to_do.append(jieba_i[min_index])
to_do.append(jieba_i[min_index+1])
if min_index - 2 >= 0:
g_check_a = jieba_i[min_index-2]
if min_index + 2 < jieba_len:
g_check_e = jieba_i[min_index+2]
print("需要处理:"+repr(to_do))
print("辅助检测:%s,%s" %(g_check_a, g_check_e))
#保存最终的结果
p_res_stage1 = {}
p_res_stage2 = {}
p_res_stage3 = {}
max_item_1 = None
max_item_2 = None
max_item_3 = None
max_pro_1 = 0
max_item_1 = None
max_pro_2 = 0
max_item_2 = None
max_pro_3 = 0
max_item_3 = None
#STAGE1 假设分词没有错误
pinyin_t = pinyin.word2pinyin_split(to_do[0],'-') + '-' + pinyin.word2pinyin_split(to_do[1],'-')
p_res_1 = {}
if pinyin_t in JIEBA_PINYIN.keys():
list_t = JIEBA_PINYIN.get(pinyin_t)
for item in list_t:
if to_do[0] != item[0:len(to_do[0])]:
continue
else:
p_res_1[item[len(to_do[0]):]] = JIEBA_HZ.get(item)
pinyin_t = pinyin.word2pinyin_split(to_do[1],'-') + '-' + pinyin.word2pinyin_split(to_do[2],'-')
p_res_2 = {}
if pinyin_t in JIEBA_PINYIN.keys():
list_t = JIEBA_PINYIN.get(pinyin_t)
for item in list_t:
if to_do[2] != item[len(to_do[1]):]:
continue
else:
p_res_2[item[0:len(to_do[1])]] = JIEBA_HZ.get(item)
#print("2.找到:%s-%s,概率%f\t" %(to_do[0],item,JIEBA_HZ.get(item)))
p_res_intr = dict.fromkeys(x for x in p_res_1 if x in p_res_2)
if p_res_intr:
max_pro_1 = 0
max_item_1 = None
for item in p_res_intr:
p_res_intr[item] = p_res_1[item]*p_res_2[item] / (p_res_1[item] + p_res_2[item])
if p_res_intr[item] > max_pro_1:
max_pro_1 = p_res_intr[item]
max_item_1 = item
print(repr(p_res_intr))
p_res_stage1 = p_res_intr
#STAGE2 假设第一和第二个合并
to_do_a = [to_do[0]+to_do[1], to_do[2]]
p_res_3 = {}
p_res_s3 = {}
pinyin_t = pinyin.word2pinyin_split(to_do_a[0],'-') + '-' + pinyin.word2pinyin_split(to_do_a[1],'-')
if pinyin_t in JIEBA_PINYIN.keys():
list_t = JIEBA_PINYIN.get(pinyin_t)
for item in list_t:
print(item)
if to_do_a[1] != item[len(to_do_a[1]):]:
continue
else:
p_res_3[item[:len(to_do_a[1])]] = JIEBA_HZ.get(item)
if g_check_a:
for item in p_res_3:
item_t = g_check_a+item
if item_t in JIEBA_HZ.keys():
p_res_s3[item] = JIEBA_HZ.get(item_t)
else:
p_res_s3 = p_res_3
p_res_intr = dict.fromkeys(x for x in p_res_3 if x in p_res_s3)
if p_res_intr:
for item in p_res_intr:
p_res_intr[item] = p_res_3[item]*p_res_s3[item] / (p_res_3[item] + p_res_s3[item])
if p_res_intr[item] > max_pro_2:
max_pro_2 = p_res_intr[item]
max_item_2 = item
p_res_stage2 = p_res_intr
#STAGE3 假设第二和第三个合并
to_do_b = [to_do[0], to_do[1]+to_do[2]]
p_res_4 = {}
p_res_s4 = {}
pinyin_t = pinyin.word2pinyin_split(to_do_b[0],'-') + '-' + pinyin.word2pinyin_split(to_do_b[1],'-')
if pinyin_t in JIEBA_PINYIN.keys():
list_t = JIEBA_PINYIN.get(pinyin_t)
for item in list_t:
if to_do_b[0] != item[0:len(to_do_b[0])]:
continue
else:
p_res_4[item[len(to_do_b[0]):]] = JIEBA_HZ.get(item)
if g_check_e:
for item in p_res_4:
item_t = item + g_check_e
if item_t in JIEBA_HZ.keys():
p_res_s4[item] = JIEBA_HZ.get(item_t)
else:
p_res_s4 = p_res_4
p_res_intr = dict.fromkeys(x for x in p_res_4 if x in p_res_s4)
if p_res_intr:
for item in p_res_intr:
p_res_intr[item] = p_res_4[item]*p_res_s4[item] / (p_res_4[item] + p_res_s4[item])
if p_res_intr[item] > max_pro_3:
max_pro_3 = p_res_intr[item]
max_item_3 = item
print(repr(p_res_intr))
p_res_stage3 = p_res_intr
#打印纠正结果
if max_item_1:
print("STAGE1:纠错结果:%s %s %s,概率%f"%(to_do[0],max_item_1,to_do[2],p_res_stage1[max_item_1]))
else:
print("STAGE1:纠错失败")
if max_item_2:
print("STAGE2:纠错结果:%s %s,概率%f"%(max_item_2,to_do_a[1],p_res_stage2[max_item_2]))
else:
print("STAGE2:纠错失败")
if max_item_3:
print("STAGE3:纠错结果:%s %s,概率%f"%(to_do_b[0],max_item_3,p_res_stage3[max_item_3]))
else:
print("STAGE3:纠错失败")
max_pro = max([max_pro_1, max_pro_2, max_pro_3])
if max_pro != 0:
if max_pro == max_pro_1:
final_words = jieba_i[0:min_index-1] + [ to_do[0], max_item_1, to_do[2] ] + jieba_i[min_index+2:jieba_len]
elif max_pro == max_pro_2:
final_words = jieba_i[0:min_index-1] + [ max_item_2, to_do_a[1] ] + jieba_i[min_index+2:jieba_len]
elif max_pro == max_pro_3:
final_words = jieba_i[0:min_index-1] + [ to_do_b[0], max_item_3 ] + jieba_i[min_index+2:jieba_len]
print("原句: "+str_test)
print("纠正:"+''.join(final_words))
return (''.join(final_words))
else:
print('纠错失败')
return None
# Max buffer size
global_q = queue.Queue(maxsize=10)
# 由DistributeThread分发,用于处理客户端请求
class ProcessPoolThread(threading.Thread):
def __init__(self, tid):
self.cur_thread = threading.Thread.__init__(self)
self.threadID = tid
def run(self):
while True:
# The Queue get是阻塞的
conn, addr = global_q.get()
self.handle_process(conn, addr)
def handle_process(self, conn, addr):
# 多个返回可能会被合并到一个数据包中
print("PROCESS T[%d]正在处理%s" %(self.threadID, repr(addr)))
req_datas = conn.recv(2048).decode()
jreq_datas = eval(req_datas)
for req_item in jreq_datas:
if req_item['CLIENT'] != 0 and req_item['TYPE'] == 'REQ_COR':
rep_data = correct_me(req_item['DATA'])
rep_url = {'CLIENT':req_item['CLIENT'],'TYPE':'REP_URL','DATA':rep_data}
jrep_url = repr(rep_url) + ','
conn.sendall(jrep_url.encode())
else:
print("UKNOWN CLIENT REQUEST!")
return
class DistributeThread(threading.Thread):
def __init__(self, host, port, tid):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.threadID = tid
self.sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def run(self):
print ("启动服务器分发线程 %d ...\n" % self.threadID)
self.sk.bind((self.host,self.port))
self.sk.listen(1)
while True:
conn, addr = self.sk.accept()
print("SERVER[%d], Recv request from %s" % (self.threadID, addr))
global_q.put((conn, addr))
print ("我怎么可能退出。。。。")
return
if __name__ == '__main__':
pynlpir.open()
#dict_file = 'MY_DICT.dat'
#print(type(dict_file))
#print(type(pynlpir.nlpir.ImportUserDict))
#用户自定义词典
#nlpir.Init(nlpir.PACKAGE_DIR, nlpir.UTF8_CODE)
#nlpir.ImportUserDict(dict_file)
#nlpir.AddUserWord('ABC')
#nlpir.Exit()
#if len(sys.argv) > 1:
# for i in range(1, len(sys.argv)):
# correct_me(sys.argv[i])
#else:
# correct_me("到乌鲁木齐邮飞怎么算")
# correct_me("仓库在钓鱼道吗难道")
#correct_me("你们从那里发货")
# correct_me("你们在市区那里发货")
# correct_me("和原来那个友什么区别")
thread_distr = DistributeThread(HOST, PORT, 99)
thread_distr.start()
threads_process = []
for i in range(20, 25):
t = ProcessPoolThread(i)
t.start()
time.sleep(2)
threads_process.append(t)
print("你好,服务器线程启动完毕,等待客户端请求...")
while True:
print("服务器还活着 ;-)...")
time.sleep(60)
pynlpir.close()