使用oracle与python进行中文分词

把看病时的主诉文本进行分割,获得词性。

从oracle读入文本,在python中分割后完成再写会oracle。

最开始使用自带的开源包,比较了3种中文分词包,thulac,snowlp,jieba,根据目测,发现还是jieba好一些。

将全量的数据分词完毕后,发现依然存在分割错误的问题。

采纳了建议尝试使用百度、腾讯、阿里巴巴开放的接口。调通了一个百度的,代码如下。

发现使用百度的包,会完全记录使用的次数,出于一些顾虑,没有将全部的数据使用百度的分词工具分完,只是试用了一下。

# -*- coding:utf-8 -*-

import cx_Oracle
import pandas as pd
from aip import AipNlp
import jieba
import jieba.analyse
import jieba.posseg
from snownlp import SnowNLP
import thulac
import numpy as np

""" 你的 APPID AK SK """ 按照百度帮助文件填写,需要注册
APP_ID = 'xxxxxxx'
API_KEY = 'xxxxxxx'
SECRET_KEY = 'xxxxxxx'
client = AipNlp(APP_ID, API_KEY, SECRET_KEY)

## 读入数据
conn = cx_Oracle.connect('scott/密码@localhost/ORCL')
curs = conn.cursor()
curs.execute('select zs from tmp_zs_cnt where zs like \'%左%\' or zs like \'%右%\'')

# 分词并写入数据库 tmp_zs_fc_1(zs,fc)
cursInput = conn.cursor()
table = 'tmp_zs_fc_1'
query = "INSERT INTO " + table + "(zs,fc,cx) VALUES ('%s', '%s', '%s')"

# df = pd.DataFrame(curs.fetchall(),columns = ["zs"])
rowCount = 0
while 1:
    rowCount += 1
    try: # 对所有报错不予解决,只记录行号
        onerow = curs.fetchone() # 编码出错
        if not onerow:
            break
        rawstring = onerow[0]
        # ss = jieba.posseg.cut(rawstring) #编码出错
        ss = client.lexer(rawstring)
        for x in ss['items']:
            zs = rawstring
            # fc = x.word
            # cx = x.flag
            fc = x['item']
            cx = x['pos']
            cursInput.execute(query % (zs, fc, cx)) # 字符串中带有'
            conn.commit()
    except Exception as e:
        print('报错的行号:',rowCount)
        continue

# 关闭游标
curs.close()
cursInput.close()
conn.close()
print("ok, program ends")

后续可能考虑如何基于现有的包,提高分词的准确率。

猜你喜欢

转载自blog.csdn.net/u012891477/article/details/86690663