第6章实战之聊天语料处理—6.7句子和向量之间的转换

1. 添加代码至word_sequence.py

    def transform(self,sentence,max_len=None):
        assert self.fitted, "WordSequence尚未进行fit操作"

        if max_len is not None:
            r=[self.PAD]*max_len
        else:
            r=[self.PAD]*len(sentence)

        for index, a in enumerate(sentence):
            if max_len is not None and index>=len(r):
                break
            r[index]=self.to_index(a)

        return np.array(r)

    def inverse_transform(self, indices, ignore_pad=False, ignore_unk=False, ignore_start=False,
                      ignore_end=False):
        ret=[]
        for i in indices:
            word=self.to_word(i)
            if word==WordSequence.PAD_TAG and ignore_pad:
                continue
            if word==WordSequence.UNK_TAG and ignore_unk:
                continue
            if word==WordSequence.START_TAG and ignore_start:
                continue
            if word==WordSequence.END_TAG and ignore_end:
                continue
            ret.append(word)

        return ret


def test():
    ws = WordSequence()
    ws.fit([
        ['你','好','啊'],
        ['你','好','哦'],
    ])

    indice = ws.transform(['我','们','好'])
    print(indice)

    back=ws.inverse_transform(indice)
    print(back)

if __name__=='__main__':
    test()

2.运行WordSequence.py

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值