已知词典dic={‘北京’,’北京大学’,’读书’},把text=’我在北京的北京大学读书’变为下面分词的标签格式。提示:可以用词典分词方法把text变为分词结果的列表,再变成标签数据。
我 o
在 o
北 b
京 i
的 o
北 b
京 i
大 i
学 i
读 b
书 i
def forward_match(dic,text):
# 分词
i = 0
word_list = []
while i<len(text):
word = text[i]
for j in range(i,len(text)+1):
long_word = text[i:j]
if long_word in dic and len(word)<len(long_word):
word = long_word
word_list.append(word)
i += len(word)
print("分词结果:",word_list)
# 确定标签
word_label_list = []
for word in word_list:
if len(word)==1:
word_label_list.append("o")
else:
for index,value in enumerate(word):
if index==0:
word_label_list.append("b")
else:
word_label_list.append("i")
return word_label_list
dic = {"北京","北京大学","读书"}
text='我在北京的北京大学读书'
word_label_list = forward_match(dic,text)
print("字列表:",[i for i in text])
print("每个字的标签值:",word_label_list)