汉语分词最大匹配算法

正向最大匹配,逆向最大匹配

汉语正向、逆向最大分词算法

汉语分词最大匹配法(Maximum Matching):

  1. 正向最大匹配算法(Forward MM)
  2. 逆向最大匹配算法(Backward MM)

算法

假设句子:$S = c_1c_2···c_n$,某一词:$w_i = c_1c_2···c_m$,$m$为词典中最长词的字数。
FMM 算法描述

  1. 令$i=0$,当前指针$p_i$指向输入字串的初始位置,执行下面的操作:
  2. 计算当前指针$p_i$到字串末端的字数(即未被切分字串的长度)$n$,如果$n=1$,转(4),结束算法。否则,令$m=$词典中最长单词的字数,如果$n<m$,令$m=n$。
  3. 从当前$p_i$起取$m$个汉字作为词$w_i$,判断:
    3.1. 如果$w_i$确实是词典中的词,则在$w_i$后添加一个切分标志,转(3.3);
    3.2. 如果$w_i$不是词典中的词且$w_i$的长度大于1,将$w_i$从右端去掉一个字,转(3.1)步;否则($w_i$的长度等于1),则在$w_i$后添加一个切分标志,将$w_i$作为单字词添加到词典中,执行(3.3)步;
    3.3. 根据$w_i$的长度修改指针$p_i$的位置,如果$p_i$指向字串末端,转(4),否则,$i=i+1$,返回(2);
  4. 输出切分结果,结束分词程序。

逆向最大匹配算法同理。

数据

人民日报语料,总共100344条样本。
样例:’/w 99/m 昆明/ns 世博会/n 组委会/j 秘书长/n 、/w 云南省/ns 副/b 省长/n 刘/nr 京/nr 介绍/v 说/v ,/w ’/w 99/m 世博会/j

代码

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
# -*- coding:utf-8 -*-
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
import seaborn
plt.style.use('fivethirtyeight')

def readFile(filename):
'''
read file return a generator, each element is one line

Parameters
----------
filename: str, filename

Returns:
----------
generator
'''
with open(filename, 'r', encoding = 'utf-8') as f:
data = f.readline().strip()
while data:
yield data
try:
data = f.readline().strip()
except:
print('read file failed in one line!')
continue

def preprocess_text(text):
'''
Parameters
----------
text: str, ’/w 99/m 昆明/ns 世博会/n 组委会/j 秘书长/n 、/w 云南省/ns

Returns
----------
str, ’99昆明世博会组委会秘书长、云南省
'''
return ''.join(map(lambda x: x[: x.rfind('/')], text.split(' ')))

def preprocess_text2(text):
'''
Parameters
----------
text: str, ’/w 99/m 昆明/ns 世博会/n 组委会/j 秘书长/n 、/w 云南省/ns

Returns
----------
str, ’/99/昆明/世博会/组委会/秘书长/、/云南省
'''
return ''.join(map(lambda x: x[:x.rfind('/')+1], text.split(' ')))

def precision_recall_f1(output, target):
'''
Parameters
----------
output, str

target, str

Returns
----------
precision, recall and f1, float
'''
def extract_index_pair(text):
o = [(0, 0)]
index = 0
for i in text:
if i != '/':
index += 1
else:
o.append((o[-1][-1], index))
else:
o.append((o[-1][-1], index))
o = set(o)
o.remove((0, 0))
return o

o = extract_index_pair(output)
t = extract_index_pair(target)

def precision_score(o, t):
count = 0
for i in t:
if i in o:
count += 1
return count / len(t)

precision, recall = precision_score(o, t), precision_score(t, o)
f1 = (2 * precision * recall) / (precision + recall)
return precision, recall, f1

def build_corpus_and_testing_text(filename, training_ratio = 0.7):
'''
forward maximum matching

Parameters
----------
filename: str

training_ratio: float, ratio of training data

Returns
----------
corpus: set

testing_text: list, each element is a sentence that need to be preprocessed
'''
corpus = set()
num_of_lines = 0
for line in readFile(filename):
num_of_lines += 1
all_index = np.arange(num_of_lines)
np.random.shuffle(all_index)
training_lines = set(all_index[:int(training_ratio * num_of_lines)].tolist())

testing_text = []
for index, line in enumerate(readFile(filename)):
if index not in training_lines:
testing_text.append(line)
continue
for temp in map(lambda x: x.split('/'), line.split(' ')):
if len(temp) != 2:
continue
word, _ = temp
if 'http' in word or 'www.' in word:
continue
corpus.add(word)
return corpus, testing_text

def split_words(line, corpus_set):
'''
forward maximum matching

Parameters
----------
line: str, a chinese string

corpus_set: set, corpus

Returns
----------
str, results
'''
n_line = len(line)
start, end = 0, n_line
result = []
while start < n_line:
# time.sleep(0.5)
# print(result)
n = n_line - start
if n == 1:
result.append(line[start:])
return '/'.join(result) + '/'
current_word = line[start: end]
if current_word in corpus_set:
result.append(current_word)
start = end
end = n_line
continue
else:
if len(current_word) == 1:
corpus_set.add(current_word)
result.append(current_word)
start = end
end = n_line
continue
end -= 1
continue
start += 1
return '/'.join(result) + '/'

def split_words_reverse(line, corpus_set):
'''
backward maximum matching

Parameters
----------
line: str, a chinese string

corpus_set: set, corpus

Returns
----------
str, results
'''
n_line = len(line)
start, end = 0, n_line
result = []
while end > 0:
# time.sleep(0.5)
# print(result)
if (end - 0) == 1:
result.append(line[start: end])
return '/'.join(reversed(result)) + '/'
current_word = line[start: end]
if current_word in corpus_set:
result.append(current_word)
end = start
start = 0
continue
else:
if len(current_word) == 1:
corpus_set.add(current_word)
result.append(current_word)
end = start
start = 0
continue
start += 1
continue
end -= 1
return '/'.join(reversed(result)) + '/'

def run(split_words_function, testing_text, corpus):
p_r_f1 = []
results = []
for index, i in enumerate(testing_text):
text = preprocess_text(i)
target = preprocess_text2(i)
output = split_words_function(text, corpus)
p_r_f1.append(precision_recall_f1(output, target))
results.append(output)

a, b, c = zip(*p_r_f1)
average_precision = sum(a) / len(a)
average_recall = sum(b) / len(b)
average_f1 = sum(c) / len(c)
print('average precision:', average_precision)
print('average recall', average_recall)
print('average F1-score', average_f1)
plt.figure(figsize = (16, 4))
plt.subplot(121)
plt.xticks(np.arange(0, 1.05, 0.1))
plt.hist(a, bins = np.arange(0, 1.05, 0.05))
plt.xlabel('precision')
plt.ylabel('frequency')
plt.title('precision')
plt.subplot(122)
plt.xticks(np.arange(0, 1.05, 0.1))
plt.hist(b, bins = np.arange(0, 1.05, 0.05))
plt.xlabel('recall')
plt.ylabel('frequency')
plt.title('recall')
plt.show()
return results, a, b, c

if __name__ == '__main__':
corpus_file = 'data/train_pd_utf8.txt'
corpus, testing_text = build_corpus_and_testing_text(corpus_file)
print('corpus size:', len(corpus))
print('testing data size:', len(testing_text))
results, a, b, c = run(split_words, testing_text, corpus)
results, a, b, c = run(split_words_reverse, testing_text, corpus)

2.6 运行结果

2.6.1 FMM运行结果

average-precision average-recall average-F1-score
0.9237 0.9198 0.9207

2.6.2 BMM运行结果

average-precision average-recall average-F1-score
0.9394 0.9269 0.9277