-
Notifications
You must be signed in to change notification settings - Fork 3
/
pre_data.py
1782 lines (1646 loc) · 65 KB
/
pre_data.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
import random
import json
import copy
import re
import time
import math
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
PAD_token = 0
cons_mode=[1,2,3]
class Lang:
"""
class to save the vocab and two dict: the word->index and index->word
"""
def __init__(self):
self.word2index = {}
self.word2count = {}
self.index2word = []
self.n_words = 0 # Count word tokens
self.num_start = 0
def add_sen_to_vocab(self, sentence): # add words of sentence to vocab
for word in sentence:
if re.search("N\d+|NUM|\d+", word):
continue
if word not in self.index2word:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word.append(word)
self.n_words += 1
else:
self.word2count[word] += 1
def trim(self, min_count): # trim words below a certain count threshold
keep_words = []
for k, v in self.word2count.items():
if v >= min_count:
keep_words.append(k)
print('keep_words %s / %s = %.4f' % (
len(keep_words), len(self.index2word), len(keep_words) / len(self.index2word)
))
# Reinitialize dictionaries
self.word2index = {}
self.word2count = {}
self.index2word = []
self.n_words = 0 # Count default tokens
for word in keep_words:
self.word2index[word] = self.n_words
self.index2word.append(word)
self.n_words += 1
def build_input_lang(self, trim_min_count): # build the input lang vocab and dict
if trim_min_count > 0:
self.trim(trim_min_count)
self.index2word = ["PAD", "NUM", "UNK"] + self.index2word
else:
self.index2word = ["PAD", "NUM"] + self.index2word
self.word2index = {}
self.n_words = len(self.index2word)
for i, j in enumerate(self.index2word):
self.word2index[j] = i
def build_output_lang(self, generate_num, copy_nums): # build the output lang vocab and dict
self.index2word = ["PAD", "EOS"] + self.index2word + generate_num + ["N" + str(i) for i in range(copy_nums)] +\
["SOS", "UNK"]
self.n_words = len(self.index2word)
for i, j in enumerate(self.index2word):
self.word2index[j] = i
def build_output_lang_for_tree(self, generate_num, copy_nums): # build the output lang vocab and dict
self.num_start = len(self.index2word)
self.index2word = self.index2word + generate_num + ["N" + str(i) for i in range(copy_nums)] + ["UNK"]
self.n_words = len(self.index2word)
for i, j in enumerate(self.index2word):
self.word2index[j] = i
def load_raw_data(filename): # load the json data to list(dict()) for MATH 23K
print("Reading lines...")
f = open(filename,'r')
js = ""
data = []
for i, s in enumerate(f):
js += s
i += 1
if i % 7 == 0: # every 7 line is a json
data_d = json.loads(js)
if "千米/小时" in data_d["equation"]:
data_d["equation"] = data_d["equation"][:-5]
data.append(data_d)
js = ""
return data
# remove the superfluous brackets
def remove_brackets(x):
y = x
if x[0] == "(" and x[-1] == ")":
x = x[1:-1]
flag = True
count = 0
for s in x:
if s == ")":
count -= 1
if count < 0:
flag = False
break
elif s == "(":
count += 1
if flag:
return x
return y
def load_mawps_data(filename): # load the json data to list(dict()) for MAWPS
print("Reading lines...")
f = open(filename,'r')
data = json.load(f)
out_data = []
for d in data:
if "lEquations" not in d or len(d["lEquations"]) != 1:
continue
x = d["lEquations"][0].replace(" ", "")
if "lQueryVars" in d and len(d["lQueryVars"]) == 1:
v = d["lQueryVars"][0]
if v + "=" == x[:len(v)+1]:
xt = x[len(v)+1:]
if len(set(xt) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = xt
out_data.append(temp)
continue
if "=" + v == x[-len(v)-1:]:
xt = x[:-len(v)-1]
if len(set(xt) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = xt
out_data.append(temp)
continue
if len(set(x) - set("0123456789.+-*/()=xX")) != 0:
continue
if x[:2] == "x=" or x[:2] == "X=":
if len(set(x[2:]) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = x[2:]
out_data.append(temp)
continue
if x[-2:] == "=x" or x[-2:] == "=X":
if len(set(x[:-2]) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = x[:-2]
out_data.append(temp)
continue
return out_data
def load_roth_data(filename): # load the json data to dict(dict()) for roth data
print("Reading lines...")
f = open(filename,'r')
data = json.load(f)
out_data = {}
for d in data:
if "lEquations" not in d or len(d["lEquations"]) != 1:
continue
x = d["lEquations"][0].replace(" ", "")
if "lQueryVars" in d and len(d["lQueryVars"]) == 1:
v = d["lQueryVars"][0]
if v + "=" == x[:len(v)+1]:
xt = x[len(v)+1:]
if len(set(xt) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = remove_brackets(xt)
y = temp["sQuestion"]
seg = y.strip().split(" ")
temp_y = ""
for s in seg:
if len(s) > 1 and (s[-1] == "," or s[-1] == "." or s[-1] == "?"):
temp_y += s[:-1] + " " + s[-1:] + " "
else:
temp_y += s + " "
temp["sQuestion"] = temp_y[:-1]
out_data[temp["iIndex"]] = temp
continue
if "=" + v == x[-len(v)-1:]:
xt = x[:-len(v)-1]
if len(set(xt) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = remove_brackets(xt)
y = temp["sQuestion"]
seg = y.strip().split(" ")
temp_y = ""
for s in seg:
if len(s) > 1 and (s[-1] == "," or s[-1] == "." or s[-1] == "?"):
temp_y += s[:-1] + " " + s[-1:] + " "
else:
temp_y += s + " "
temp["sQuestion"] = temp_y[:-1]
out_data[temp["iIndex"]] = temp
continue
if len(set(x) - set("0123456789.+-*/()=xX")) != 0:
continue
if x[:2] == "x=" or x[:2] == "X=":
if len(set(x[2:]) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = remove_brackets(x[2:])
y = temp["sQuestion"]
seg = y.strip().split(" ")
temp_y = ""
for s in seg:
if len(s) > 1 and (s[-1] == "," or s[-1] == "." or s[-1] == "?"):
temp_y += s[:-1] + " " + s[-1:] + " "
else:
temp_y += s + " "
temp["sQuestion"] = temp_y[:-1]
out_data[temp["iIndex"]] = temp
continue
if x[-2:] == "=x" or x[-2:] == "=X":
if len(set(x[:-2]) - set("0123456789.+-*/()")) == 0:
temp = d.copy()
temp["lEquations"] = remove_brackets(x[2:])
y = temp["sQuestion"]
seg = y.strip().split(" ")
temp_y = ""
for s in seg:
if len(s) > 1 and (s[-1] == "," or s[-1] == "." or s[-1] == "?"):
temp_y += s[:-1] + " " + s[-1:] + " "
else:
temp_y += s + " "
temp["sQuestion"] = temp_y[:-1]
out_data[temp["iIndex"]] = temp
continue
return out_data
# for testing equation
# def out_equation(test, num_list):
# test_str = ""
# for c in test:
# if c[0] == "N":
# x = num_list[int(c[1:])]
# if x[-1] == "%":
# test_str += "(" + x[:-1] + "/100.0" + ")"
# else:
# test_str += x
# elif c == "^":
# test_str += "**"
# elif c == "[":
# test_str += "("
# elif c == "]":
# test_str += ")"
# else:
# test_str += c
# return test_str
def transfer_num(data): # transfer num into "NUM"
print("Transfer numbers...")
pattern = re.compile("\d*\(\d+/\d+\)\d*|\d+\.\d+%?|\d+%?")
pairs = []
generate_nums = []
generate_nums_dict = {}
copy_nums = 0
count_empty=0
UNK2word_vocab={}
input1=open("data//UNK2word_vocab","r").readlines()
for word in input1:
UNK2word_vocab[word.strip().split("###")[0]]=word.strip().split("###")[1]
for d in data:
nums = []
input_seq = []
seg_line = d["segmented_text"].encode("UTF-8").strip()
for UNK_word in UNK2word_vocab:
if UNK_word in seg_line:
seg_line=seg_line.replace(UNK_word,UNK2word_vocab[UNK_word])
seg=seg_line.split(" ")
equations = d["equation"][2:]
for s in seg:
pos = re.search(pattern, s)
if pos and pos.start() == 0:
nums.append(s[pos.start(): pos.end()])
input_seq.append("NUM")
if pos.end() < len(s):
input_seq.append(s[pos.end():])
else:
if len(s)>0:
input_seq.append(s)
else:
count_empty=count_empty+1
if copy_nums < len(nums):
copy_nums = len(nums)
nums_fraction = []
for num in nums:
if re.search("\d*\(\d+/\d+\)\d*", num):
nums_fraction.append(num)
nums_fraction = sorted(nums_fraction, key=lambda x: len(x), reverse=True)
def seg_and_tag(st): # seg the equation and tag the num
res = []
for n in nums_fraction:
if n in st:
p_start = st.find(n)
p_end = p_start + len(n)
if p_start > 0:
res += seg_and_tag(st[:p_start])
if nums.count(n) == 1:
res.append("N"+str(nums.index(n)))
else:
res.append(n)
if p_end < len(st):
res += seg_and_tag(st[p_end:])
return res
pos_st = re.search("\d+\.\d+%?|\d+%?", st)
if pos_st:
p_start = pos_st.start()
p_end = pos_st.end()
if p_start > 0:
res += seg_and_tag(st[:p_start])
st_num = st[p_start:p_end]
if nums.count(st_num) == 1:
res.append("N"+str(nums.index(st_num)))
else:
res.append(st_num)
if p_end < len(st):
res += seg_and_tag(st[p_end:])
return res
for ss in st:
res.append(ss)
return res
out_seq = seg_and_tag(equations)
for s in out_seq: # tag the num which is generated
if s[0].isdigit() and s not in generate_nums and s not in nums:
generate_nums.append(s)
generate_nums_dict[s] = 0
if s in generate_nums and s not in nums:
generate_nums_dict[s] = generate_nums_dict[s] + 1
num_pos = []
for i, j in enumerate(input_seq):
if j == "NUM":
num_pos.append(i)
assert len(nums) == len(num_pos)
#unit_list,rule3_list=get_constraint_unit(input_seq,num_pos)
#new_input_seq,new_num_pos =get_new_inputseq(input_seq,unit_list,rule3_list,num_pos)
# pairs.append((input_seq, out_seq, nums, num_pos, d["ans"]))
#* N0 N1 + N0 N2 * N1 N2 爱心 超市 运 来 NUM 千克 大米 , 卖 了 NUM 天 后 , 还 剩 NUM 千克 , 平均 每天 卖 大米 多少 千克 ?
#print(" ".join(new_input_seq))
pairs.append((input_seq, out_seq, nums, num_pos))
print("count_empty")
print(count_empty)
temp_g = []
for g in generate_nums:
if generate_nums_dict[g] >= 5:
temp_g.append(g)
return pairs, temp_g, copy_nums
def get_new_inputseq(input_seq,unit_list,rule3_list,num_pos):
#rule3_list [1,2] whether this pos is a multiple NUM
#unit_list [排###个###排] unit for each num
cons_word_list=[]
for i in range(0,len(num_pos)-1):
if 3 in cons_mode:
if i in rule3_list:
cons_word_list.append("/")
N1_word="N"+str(i)
N2_word="N"+str(i)
cons_word_list.append(N1_word)
cons_word_list.append(N2_word)
for j in range(i+1,len(num_pos)):
if i !=j:
if 1 in cons_mode:
if unit_list[i]!="" and unit_list[j]!="" and unit_list[i]==unit_list[j]:
cons_word_list.append("+")
N1_word="N"+str(i)
N2_word="N"+str(j)
cons_word_list.append(N1_word)
cons_word_list.append(N2_word)
if 2 in cons_mode:
if unit_list[i]!="" and unit_list[j]!="" and unit_list[i]!=unit_list[j]:
cons_word_list.append("*")
N1_word="N"+str(i)
N2_word="N"+str(j)
cons_word_list.append(N1_word)
cons_word_list.append(N2_word)
input_seq=cons_word_list+input_seq
new_num_pos = []
for i, j in enumerate(input_seq):
if j == "NUM":
new_num_pos.append(i)
assert len(new_num_pos) == len(num_pos)
return input_seq,new_num_pos
def transfer_english_num(data): # transfer num into "NUM"
print("Transfer numbers...")
pattern = re.compile("\d+,\d+|\d+\.\d+|\d+")
pairs = []
generate_nums = {}
copy_nums = 0
for d in data:
nums = []
input_seq = []
seg = d["sQuestion"].strip().split(" ")
equations = d["lEquations"]
for s in seg:
pos = re.search(pattern, s)
if pos:
if pos.start() > 0:
input_seq.append(s[:pos.start()])
num = s[pos.start(): pos.end()]
# if num[-2:] == ".0":
# num = num[:-2]
# if "." in num and num[-1] == "0":
# num = num[:-1]
nums.append(num.replace(",", ""))
input_seq.append("NUM")
if pos.end() < len(s):
input_seq.append(s[pos.end():])
else:
input_seq.append(s)
if copy_nums < len(nums):
copy_nums = len(nums)
eq_segs = []
temp_eq = ""
for e in equations:
if e not in "()+-*/":
temp_eq += e
elif temp_eq != "":
count_eq = []
for n_idx, n in enumerate(nums):
if abs(float(n) - float(temp_eq)) < 1e-4:
count_eq.append(n_idx)
if n != temp_eq:
nums[n_idx] = temp_eq
if len(count_eq) == 0:
flag = True
for gn in generate_nums:
if abs(float(gn) - float(temp_eq)) < 1e-4:
generate_nums[gn] += 1
if temp_eq != gn:
temp_eq = gn
flag = False
if flag:
generate_nums[temp_eq] = 0
eq_segs.append(temp_eq)
elif len(count_eq) == 1:
eq_segs.append("N"+str(count_eq[0]))
else:
eq_segs.append(temp_eq)
eq_segs.append(e)
temp_eq = ""
else:
eq_segs.append(e)
if temp_eq != "":
count_eq = []
for n_idx, n in enumerate(nums):
if abs(float(n) - float(temp_eq)) < 1e-4:
count_eq.append(n_idx)
if n != temp_eq:
nums[n_idx] = temp_eq
if len(count_eq) == 0:
flag = True
for gn in generate_nums:
if abs(float(gn) - float(temp_eq)) < 1e-4:
generate_nums[gn] += 1
if temp_eq != gn:
temp_eq = gn
flag = False
if flag:
generate_nums[temp_eq] = 0
eq_segs.append(temp_eq)
elif len(count_eq) == 1:
eq_segs.append("N" + str(count_eq[0]))
else:
eq_segs.append(temp_eq)
# def seg_and_tag(st): # seg the equation and tag the num
# res = []
# pos_st = re.search(pattern, st)
# if pos_st:
# p_start = pos_st.start()
# p_end = pos_st.end()
# if p_start > 0:
# res += seg_and_tag(st[:p_start])
# st_num = st[p_start:p_end]
# if st_num[-2:] == ".0":
# st_num = st_num[:-2]
# if "." in st_num and st_num[-1] == "0":
# st_num = st_num[:-1]
# if nums.count(st_num) == 1:
# res.append("N"+str(nums.index(st_num)))
# else:
# res.append(st_num)
# if p_end < len(st):
# res += seg_and_tag(st[p_end:])
# else:
# for sst in st:
# res.append(sst)
# return res
# out_seq = seg_and_tag(equations)
# for s in out_seq: # tag the num which is generated
# if s[0].isdigit() and s not in generate_nums and s not in nums:
# generate_nums.append(s)
num_pos = []
for i, j in enumerate(input_seq):
if j == "NUM":
num_pos.append(i)
if len(nums) != 0:
pairs.append((input_seq, eq_segs, nums, num_pos))
temp_g = []
for g in generate_nums:
if generate_nums[g] >= 5:
temp_g.append(g)
return pairs, temp_g, copy_nums
def transfer_roth_num(data): # transfer num into "NUM"
print("Transfer numbers...")
pattern = re.compile("\d+,\d+|\d+\.\d+|\d+")
pairs = {}
generate_nums = {}
copy_nums = 0
for key in data:
d = data[key]
nums = []
input_seq = []
seg = d["sQuestion"].strip().split(" ")
equations = d["lEquations"]
for s in seg:
pos = re.search(pattern, s)
if pos:
if pos.start() > 0:
input_seq.append(s[:pos.start()])
num = s[pos.start(): pos.end()]
# if num[-2:] == ".0":
# num = num[:-2]
# if "." in num and num[-1] == "0":
# num = num[:-1]
nums.append(num.replace(",", ""))
input_seq.append("NUM")
if pos.end() < len(s):
input_seq.append(s[pos.end():])
else:
input_seq.append(s)
if copy_nums < len(nums):
copy_nums = len(nums)
eq_segs = []
temp_eq = ""
for e in equations:
if e not in "()+-*/":
temp_eq += e
elif temp_eq != "":
count_eq = []
for n_idx, n in enumerate(nums):
if abs(float(n) - float(temp_eq)) < 1e-4:
count_eq.append(n_idx)
if n != temp_eq:
nums[n_idx] = temp_eq
if len(count_eq) == 0:
flag = True
for gn in generate_nums:
if abs(float(gn) - float(temp_eq)) < 1e-4:
generate_nums[gn] += 1
if temp_eq != gn:
temp_eq = gn
flag = False
if flag:
generate_nums[temp_eq] = 0
eq_segs.append(temp_eq)
elif len(count_eq) == 1:
eq_segs.append("N"+str(count_eq[0]))
else:
eq_segs.append(temp_eq)
eq_segs.append(e)
temp_eq = ""
else:
eq_segs.append(e)
if temp_eq != "":
count_eq = []
for n_idx, n in enumerate(nums):
if abs(float(n) - float(temp_eq)) < 1e-4:
count_eq.append(n_idx)
if n != temp_eq:
nums[n_idx] = temp_eq
if len(count_eq) == 0:
flag = True
for gn in generate_nums:
if abs(float(gn) - float(temp_eq)) < 1e-4:
generate_nums[gn] += 1
if temp_eq != gn:
temp_eq = gn
flag = False
if flag:
generate_nums[temp_eq] = 0
eq_segs.append(temp_eq)
elif len(count_eq) == 1:
eq_segs.append("N" + str(count_eq[0]))
else:
eq_segs.append(temp_eq)
# def seg_and_tag(st): # seg the equation and tag the num
# res = []
# pos_st = re.search(pattern, st)
# if pos_st:
# p_start = pos_st.start()
# p_end = pos_st.end()
# if p_start > 0:
# res += seg_and_tag(st[:p_start])
# st_num = st[p_start:p_end]
# if st_num[-2:] == ".0":
# st_num = st_num[:-2]
# if "." in st_num and st_num[-1] == "0":
# st_num = st_num[:-1]
# if nums.count(st_num) == 1:
# res.append("N"+str(nums.index(st_num)))
# else:
# res.append(st_num)
# if p_end < len(st):
# res += seg_and_tag(st[p_end:])
# else:
# for sst in st:
# res.append(sst)
# return res
# out_seq = seg_and_tag(equations)
# for s in out_seq: # tag the num which is generated
# if s[0].isdigit() and s not in generate_nums and s not in nums:
# generate_nums.append(s)
num_pos = []
for i, j in enumerate(input_seq):
if j == "NUM":
num_pos.append(i)
if len(nums) != 0:
pairs[key] = (input_seq, eq_segs, nums, num_pos)
temp_g = []
for g in generate_nums:
if generate_nums[g] >= 5:
temp_g.append(g)
return pairs, temp_g, copy_nums
# Return a list of indexes, one for each word in the sentence, plus EOS
def indexes_from_sentence(lang, sentence, tree=False):
res = []
for word in sentence:
if len(word) == 0:
continue
if word in lang.word2index:
res.append(lang.word2index[word])
else:
res.append(lang.word2index["UNK"])
if "EOS" in lang.index2word and not tree:
res.append(lang.word2index["EOS"])
return res
def indexes_to_sentence(lang, index_list, tree=False):
res = []
for index in index_list:
if index < lang.n_words:
res.append(lang.index2word[index])
return res
def get_file_dict_vocab_by_file():
file_dict_vocab={}
file1=open("hownet//hownet_dict_vocab").readlines()
print(file1[0])
for x in file1:
x_list=x.strip().split("###")
word=x_list[0].encode('utf-8')
word_list=[y.encode('utf-8') for y in x_list[1].split(" ")]
file_dict_vocab[word]=word_list
return file_dict_vocab
'''
def get_edge_matrix(hownet_dict_vocab,input_list):
input_edge=[]
for i in range(len(input_list)):
temp_list=[]
for j in range(len(input_list)):
temp_list.append(0)
input_edge.append(temp_list)
for i in range(len(input_list)):
word1 = input_list[i]
if word1 in hownet_dict_vocab:
cate1 = hownet_dict_vocab[word1]
if len(cate1) >0:
for j in range(len(input_list)):
word2= input_list[j]
if word2 in cate1:
input_edge[i][j]=1
return input_edge
'''
def get_common_word(input_list):
input_edge=[]
for i in range(len(input_list)):
temp_list=[]
for j in range(len(input_list)):
temp_list.append(0)
input_edge.append(temp_list)
for i in range(len(input_list)):
word1 = input_list[i]
for j in range(len(input_list)):
word2= input_list[j]
if i==j:
input_edge[i][j]=1
elif len(word1)>3 and word1!="NUM":
if word2 in word1 or word2==word1:
input_edge[i][j]=1
return input_edge
def time_since(s): # compute time
m = math.floor(s / 60)
s -= m * 60
h = math.floor(m / 60)
m -= h * 60
return '%dh %dm %ds' % (h, m, s)
def generate_how_dict_vocab(lang):
hownet_dict_vocab={}
hownet_dict_all={}
hownet_dict_category={}
vocab_list=[]
uselese_tag=["属性值","文字","属性","ProperName|专","surname|姓","部件","人","human|人","time|时间"]
index_=0
start = time.time()
file1=open("hownet//hownet_dict_all").readlines()
for x in file1:
x_list=x.strip().split("###")
word=x_list[0].encode('utf-8')
if len(word) > 3:
#print(word)
#print(len(word))
word_list=[]
if len(x_list[1])!=0:
for y in x_list[1].strip().split(" "):
y=y.encode('utf-8')
if y not in uselese_tag and len(y)>0:
word_list.append(y)
hownet_dict_all[word]=word_list
vocab_list.append(word)
for cate_ in word_list:
if cate_ in hownet_dict_category:
category_list=hownet_dict_category[cate_]
if word not in category_list:
hownet_dict_category[cate_].append(word)
else:
category_list=[]
category_list.append(word)
hownet_dict_category[cate_]=category_list
print(hownet_dict_all["电话线"])
start = time.time()
count_all=0
hownet_dict_tag={}
for i in range(len(vocab_list)):
word1=vocab_list[i]
cate1=hownet_dict_all[word1]
if len(cate1)==0:
empty_list=[]
hownet_dict_vocab[word1]=empty_list
else:
for word_ in cate1:
if len(word_) >0 and len(word1)>0 and word1 !=None:
if word_ not in hownet_dict_tag:
empty_list=[]
hownet_dict_tag[word_]=empty_list
word_list=hownet_dict_tag[word_]
if word1 not in word_list:
word_list.append(word1)
hownet_dict_tag[word_]=word_list
connect_word=[]
for j in range(len(vocab_list)):
if i!=j:
word2=vocab_list[j]
cate2=hownet_dict_all[word2]
flag=0
for word_ in cate1:
if word_ in cate2:
#print(word_+"#"+word1+"#"+word2)
flag=1
break
if flag==1:
count_all+=1
connect_word.append(word2)
hownet_dict_vocab[word1]=connect_word
print("training time", time_since(time.time() - start))
print(len(vocab_list))
print(count_all)
output=open("hownet//hownet_dict_vocab","w")
for word in hownet_dict_vocab:
output.write(word+"###"+" ".join(hownet_dict_vocab[word])+"\n")
output=open("hownet//hownet_dict_tag","w")
for word in hownet_dict_tag:
output.write(word+"###"+" ".join(hownet_dict_tag[word])+"\n")
output=open("hownet//hownet_dict_category","w")
output1=open("hownet//hownet_category_vocab","w")
category_vocab=[]
category_vocab.append("PAD")
output1.write("PAD"+"\n")
for word in hownet_dict_category:
output.write(word+"###"+" ".join(hownet_dict_category[word])+"\n")
category_vocab.append(word)
output1.write(word+"\n")
return hownet_dict_all,hownet_dict_category,category_vocab
def get_file_dict_vocab_by_file():
file_dict_vocab={}
file1=open("hownet//hownet_dict_vocab").readlines()
print(file1[0])
for x in file1:
x_list=x.strip().split("###")
word=x_list[0].encode('utf-8')
word_list=[y.encode('utf-8') for y in x_list[1].split(" ")]
file_dict_vocab[word]=word_list
return file_dict_vocab
def get_edge_matrix(hownet_dict_vocab,input_list):
input_edge=[]
for i in range(len(input_list)):
temp_list=[]
for j in range(len(input_list)):
temp_list.append(0)
input_edge.append(temp_list)
for i in range(len(input_list)):
word1 = input_list[i]
input_edge[i][i]=1
#if i>0:
# input_edge[i][i-1]=1
#if i<len(input_list)-1:
# input_edge[i][i+1]=1
if word1 in hownet_dict_vocab:
cate1 = hownet_dict_vocab[word1]
if len(cate1) >0:
for j in range(len(input_list)):
word2= input_list[j]
#if word2 in word1
if word2==word1 and len(word1)>3 and word1!="NUM":
input_edge[i][j]=1
input_edge[j][i]=1
'''
elif word2 in word1 and len(word1)>3 and word1!="NUM":
input_edge[i][j]=1
input_edge[j][i]=1
elif word1 in word2 and len(word2)>3 and word2!="NUM":
input_edge[i][j]=1
input_edge[j][i]=1
if word2 in cate1:
input_edge[i][j]=1
input_edge[j][i]=1
'''
return input_edge
def get_unit_vocab(filename):
x_idx_to_word=[]
x_word_to_idx={}
encode_vocab_dataset = open(filename).readlines()
for line in encode_vocab_dataset:
if "###" in line:
list_word = line.strip().split("###")
for word in list_word:
x_idx_to_word.append(word)
x_word_to_idx[word]=list_word[0]
else:
x_idx_to_word.append(line.strip())
x_word_to_idx[line.strip()]=line.strip()
x_idx_to_word.sort(key = lambda i:len(i),reverse=True)
return x_idx_to_word, x_word_to_idx
unit_word_list, unit_syno_to_word=get_unit_vocab("Unit//unit_vocabulary+-")
not_unit_word_list, not_unit_syno_to_word=get_unit_vocab("Unit//not_unit_vocabulary")
def get_constraint_unit(input_list,num_pos):
rule3_list=[]
list_front=["的","占","了"]
list_after=[",",".",",","。"]
count_index=0
for i in range(len(input_list)-1):
if input_list[i]=="NUM":
flag=0
if input_list[i+1]=="倍":
if num_pos[count_index]==i:
rule3_list.append(count_index)
else:
print("*************************")
print(input_list)
print(num_pos)
elif i>0 and input_list[i-1] in list_front and input_list[i+1] not in unit_word_list:
if num_pos[count_index]==i:
rule3_list.append(count_index)
else:
print("*************************")
print(input_list)
print(num_pos)
count_index+=1
unit_list=[]
for i in range(len(input_list)):
if input_list[i]=="NUM":
str_temp=" ".join(input_list[i+1:])
flag=0
for word in unit_word_list:
word1=word+" "
if str_temp.startswith(word1):
flag=1
unit_temp=unit_syno_to_word[word]
unit_list.append(unit_temp)
break
if flag==0:
unit_temp=""
unit_list.append(unit_temp)
#print(" ".join(input_list))
#print(rule3_list)
#print("###".join(unit_list))
if len(unit_list)!=len(num_pos):
print("*************************")
print(input_list)
print(num_pos)
'''
#not_unit 的 倍
for word in not_unit_word_list:
word1=word+" "
if str_temp.startswith(word1) or str_temp==word:
unit_temp=not_unit_syno_to_word[word]
break
if unit_temp=="__UNK__" and str_temp!="":
not_solve_flag+=n1+" "
str_number_unit_list.append(n1+"***"+number1+"***"+"__UNK__")
'''
#rule3_list [1,2] whether this pos is a multiple NUM
#unit_list [排,个,排] unit for each num
return unit_list,rule3_list
def get_middle_exp(output_list):
operator=["+", "-","*", "/", "^"]
middle_exp=[]
for exp in output_list:
if exp in operator:
list_exp=[exp]
else:
list_exp=[exp,exp,exp]
for i in range(len(middle_exp)-1,-1,-1):
curr_list=middle_exp[i]
if curr_list[0] in operator:
if len(curr_list)<3:
middle_exp[i].append(exp)
break
middle_exp.append(list_exp)
assert len(middle_exp) == len(output_list)
return middle_exp
def indexes_from_middle_output(lang, sentence, tree=False):
res = []
for word_list in sentence:
temp_res=[]
if len(word_list)==2:
word_list.append(word_list[-1])
if len(word_list)==1:
word_list.append(word_list[0])