HIT中文自动分词

数据集借用了nlp专业的中文自动分词数据集,使用的是反向最大分词,只处理了前1000个词

正确率为13.9%

共拥有三个文件

datamaker.py是已经分好的文件

import re


def not_empty(s):  # 判断是否为空
    return s and s.strip()


file_in = open('seg&pos.txt', 'r')
file_out = open('dict.txt', 'w')

ans = ['']
for line in file_in.readlines()[:1000]:
    line_now = re.split('[/|\[|\]][a-zA-Z]*[ ]*', line)  # 正则表达式分块
    ans.extend(line_now[1:])
ans = list(dict.fromkeys(ans).keys())  # 转变为dictionary去重
ans = list(filter(not_empty, ans))  # 除去空字符
ans.sort(key=lambda i: len(i), reverse=True)  # 对字符串进行排序
for line in ans:
    file_out.write(line + ' ')
file_in.close()
file_out.close()

solve.py是反向最大分词的程序。

import re


def not_empty(s):  # 判断是否为空
    return s and s.strip()


file_in1 = open('sent.txt', 'r')
file_in2 = open('dict.txt', 'r')
file_out = open('seg_BMM.txt', 'w')

dict_now = re.split('[ ]+', file_in2.readline())  # 正则表达式分块
dict_now = list(dict.fromkeys(dict_now).keys())  # 转变为dictionary去重
dict_now = list(filter(not_empty, dict_now))  # 除去空字符
dict_now.sort(key=lambda i: len(i), reverse=True)  # 对字符串进行排序
dictionary = []
for key in dict_now:
    dictionary.append(key.strip())  # 最后的词表
# print(dict_now)
# print(len(dict_now))
# print(len(file_in1.readlines()))

cnt = 0
for line in file_in1.readlines()[:1000]:
    cnt += 1
    # print(cnt)
    ans_now = []
    sam = line[19:len(line) - 1]
    # print(sam)
    lens = len(sam)
    # print(lens)
    while lens:
        maxn = min(lens, len(dictionary))
        word = sam[lens - maxn:lens]
        while word not in dictionary:
            if len(word) == 1:
                break
            word = word[1:]
        lens = lens - len(word)
        ans_now.insert(0, lens + 19)
    ans = list(line)
    # print(ans_now)
    for key in reversed(ans_now):
        ans.insert(key, '$$$')  # 将分词结果分隔
    # print(ans_now)
    file_out.write(''.join(ans))
    # print(''.join(ans))
    # break
file_in1.close()
file_in2.close()
file_out.close()

test.py是对于结果进行测试的程序。

import re

file_in1 = open('seg&pos.txt', 'r')
file_in2 = open('seg_BMM.txt', 'r')
cnt = 0
f = file_in1.readlines()
num = 0
for line in file_in2.readlines():
    line1 = re.split('###', line)   # 正则表达式分块
    line2 = re.split('[/|\[|\]][a-zA-Z]*[ ]*', f[cnt])  # 正则表达式分块
    if line1 == line2:
        print(cnt)
        num += 1
    cnt += 1
print(num / cnt)  # 正确率为正确句子数/错误句子数

  

posted @ 2020-10-19 19:46  古城独钓  阅读(127)  评论(0编辑  收藏  举报