
# -*- coding:utf-8 -*-
import CRFPP
import re


class TagParse:
    def __init__(self, tagger):
        self.tagger = tagger

    def get_type(self, j):
        if re.match(r'\d', j):
            return 'num'
        elif j in '一二三四五六七八九十':
            return 'cn'
        elif re.match(u'[\u4e00-\u9fa5]', j):
            return 'ch'
        else:
            return 'b'

    def sequence_init(self, sequence):
        self.tagger.clear()
        for word in sequence.strip():
            word = word.strip()
            if word:
                word = word + '\t' + self.get_type(word)
                self.tagger.add(word + "\t")
        self.tagger.parse()

    def get_val(self, sequence):
        """
        得到句子的标签
        :param sequence: 一个句子,str
        :return: x_res:句子中一个个字符,list;y_res:每个字符对应的预测标签,list
        """
        self.sequence_init(sequence)
        size = self.tagger.size()

        x_res = []
        y_res = []
        for i in range(0, size):
            x_res.append(self.tagger.x(i, 0))
            y_res.append(self.tagger.y2(i))
        return x_res, y_res

    def get_tag_val(self, sequence):
        """
        按标签将句子分块
        :param sequence:一个句子,str
        :return:[["xxx1",标签1],["xxxx2","标签2"],["xxx3",""标签3].....]
        """
        char_list, tag_list = self.get_val(sequence)
        c = [0]
        c1 = []

        for i in range(len(tag_list) - 1):
            if tag_list[i] != tag_list[i + 1]:
                c.append(i + 1)
                c1.append(i + 1)
        c1.append(len(sequence))
        res = []
        for i, j in zip(c, c1):
            res.append([''.join(char_list[i:j]), tag_list[i]])
            # char_list1 = char_list[i:j]
            # char_list_new = [''.join(char_list1)]
            # tag_list1 = tag_list[i]
            # res_dict = dict(map(lambda x, y: [x, y], tag_list1, char_list_new))
            # res.append(res_dict)

        return res


if __name__ == '__main__':
    taggers = CRFPP.Tagger("-m " + './model/crf2.model')
    tb = TagParse(taggers)
    # print(tb.get_tag_val('二、非选择题(共160分。36-42为必考题,43-47为选考题。)'))
    # print(tb.get_tag_val('一、选择题〈1-20每题1.5分,21-30每题2分,共50分'))
    print(tb.get_tag_val('任务型阅读。（共5小题，每小题2分，计10分）阅读短文，并按照要求完成66~70题'))
    # print(tb.get_tag_val('一、选择题(共25小题,每小题2分,共50分'))
    # print(tb.get_tag_val('27.(按要求给分,共12分)'))
    # print(tb.get_tag_val('53(10分)'))
    # print(tb.get_tag_val('一、选择题(每小题4分,共计40分。1至6小题单选,7至10小题多选,全对得4分,选对但不全得2分,不选或选错不得分)'))