jieba中文词性表注和CRF命名实体识别代码示例

import jieba
import jieba.posseg as posseg
import re
from datetime import datetime,timedelta
from dateutil.parser import parser


# 中文词性标注和命名实体识别
sent = "中文分词是文本处理不可或缺的一步!"
seglist = posseg.cut(sent)
# print(seglist)
print(''.join(['{0}/{1}'.format(w, t) for w, t in seglist]))
# 中文/nz分词/n是/v文本处理/n不可或缺/l的/uj一步/m!/x

# 日期识别

UTIL_CN_NUM = {'零': 0, '一': 1, '二': 2, '两': 2, '三': 3, '四': 4,
               '五': 5, '六': 6, '七': 7, '八': 8, '九': 9,
               '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
               '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

UTIL_CN_UNIT = {'十': 10, '百': 100, '千': 1000, '万': 10000}


def cn2dig(src):
    if src == "":
        return None
    m = re.match("\\d+", src)
    if m:
        return int(m.group(0))
    rsl = 0
    unit = 1
    for item in src[::-1]:
        if item in UTIL_CN_UNIT.keys():
            unit = UTIL_CN_UNIT[item]
        elif item in UTIL_CN_NUM.keys():
            num = UTIL_CN_NUM[item]
            rsl += num * unit
        else:
            return None
    if rsl < unit:
        rsl += unit
    return rsl


def year2dig(year):
    res = ''
    for item in year:
        if item in UTIL_CN_NUM.keys():
            res = res + str(UTIL_CN_NUM[item])
        else:
            res = res + item
    m = re.match("\\d+"
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个使用CNN-CRF模型进行命名实体识别代码示例: ```python import tensorflow as tf import numpy as np class CNN_CRF(object): def __init__(self, sequence_length, num_classes, vocab_size, embedding_size, filter_sizes, num_filters, hidden_dim, l2_reg_lambda=0.0): self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x") self.input_y = tf.placeholder(tf.int32, [None, sequence_length], name="input_y") self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob") self.sequence_length = sequence_length l2_loss = tf.constant(0.0) with tf.name_scope("embedding"): self.W = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), name="W") self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x) self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) pooled_outputs = [] for i, filter_size in enumerate(filter_sizes): with tf.name_scope("conv-maxpool-%s" % filter_size): filter_shape = [filter_size, embedding_size, 1, num_filters] W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") conv = tf.nn.conv2d( self.embedded_chars_expanded, W, strides=[1, 1, 1, 1], padding="VALID", name="conv") h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu") pooled = tf.nn.max_pool( h, ksize=[1, sequence_length - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name="pool") pooled_outputs.append(pooled) num_filters_total = num_filters * len(filter_sizes) h_pool = tf.concat(pooled_outputs, 3) self.h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total]) with tf.name_scope("dropout"): self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob) with tf.name_scope("output"): W = tf.get_variable( "W", shape=[num_filters_total, hidden_dim], initializer=tf.contrib.layers.xavier_initializer()) b = tf.Variable(tf.constant(0.1, shape=[hidden_dim]), name="b") self.hidden_output = tf.nn.xw_plus_b(self.h_drop, W, b, name="hidden_output") self.hidden_output_expanded = tf.expand_dims(self.hidden_output, -1) with tf.name_scope("crf"): self.transition_params = tf.Variable(tf.random_uniform([num_classes, num_classes], -0.1, 0.1), name="transition_params") self.log_likelihood, self.transition_params = tf.contrib.crf.crf_log_likelihood( self.hidden_output, self.input_y, self.sequence_length, self.transition_params) self.loss = tf.reduce_mean(-self.log_likelihood) with tf.name_scope("accuracy"): self.prediction = tf.argmax(self.hidden_output, 1, name="prediction") correct_predictions = tf.equal(self.prediction, tf.argmax(self.input_y, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy") self.params = [param for param in tf.trainable_variables() if 'embedding' not in param.name] l2_reg_lambda = tf.constant(l2_reg_lambda) l2_loss += tf.nn.l2_loss(W) l2_loss += tf.nn.l2_loss(b) self.loss += l2_reg_lambda * l2_loss ``` 这里使用的是TensorFlow框架,模型结构包括了卷积神经网络和条件随机场。其中,卷积神经网络用于提取输入句子中的特征,而条件随机场则用于对提取到的特征进行标注,得到最终的命名实体识别结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值