中文分词并将结果存入数据库

核心步骤:

  • 创建数据库连接
def get_conn():
    """
    获取连接和游标
    :return:
    """
    conn=pymysql.connect(host="127.0.0.1",
                         user="root",
                         password="000000",
                         db="news",
                         charset="utf8")
    cursor=conn.cursor()
    return conn,cursor

def close_conn(conn, cursor):
    """
    关闭连接和游标
    :param conn:
    :param cursor:
    :return:
    """
    if cursor:
        cursor.close()
    if conn:
        conn.close()
  • 读取文件
fn = open('F:\\PyCharm\\newsProject\\file\\youxi.txt', 'rt', encoding='utf-8')  # 打开文件
string_data = fn.read()  # 读出整个文件
fn.close()  # 关闭文件
  • 文本预处理
pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')  # 定义正则表达式匹配模式
string_data = re.sub(pattern, '', string_data)  # 将符合模式的字符去除
  • 文本分词
seg_list_exact = jieba.cut(string_data, cut_all=False)  # 精确模式分词
object_list = []
  • 去除停用词(停用词文件:stopword.txt)
remove_words = set()
fr = open('F:\\PyCharm\\newsProject\\stopword\\stopword.txt', encoding = 'UTF-8')
for word in fr:
    remove_words.add(str(word).strip())
fr.close()
for word in seg_list_exact:  # 循环读出每个分词
    if word not in remove_words:  # 如果不在去除词库中
        object_list.append(word)  # 分词追加到列表
  • 词频统计并导入数据库
word_counts = collections.Counter(object_list)  # 对分词做词频统计
word_counts_top10 = word_counts.most_common(100)  # 获取前10最高频的词
print(word_counts_top10)  # 输出检查
conn,course= get_conn()
for i in word_counts_top10:
    sql="insert into result_game (name,values_data) values(%s,%s)"
    course.execute(sql,i)
conn.commit()
close_conn(conn,course)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值