python提取文本关键词

python提取关键词textrank算法,将数据库中的数据提取出来,然后进行分析,代码如下

import pymysql
import jieba
from textrank4zh import TextRank4Keyword,TextRank4Sentence
import logging

jieba.setLogLevel(logging.INFO)
#消除日志

def get_key_words(text,num=3):
    tr4w=TextRank4Keyword()
    tr4w.analyze(text,lower=True)
#分析文本 key_words=tr4w.get_keywords(num)
#提取关键词,num是指关键词的个数 return [item.word for item in key_words] db = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='cs', charset='utf8')
#连接数据库 cursor = db.cursor()
#使用cursor方法创建一个游标 sql = "select shuzi from 单位" cursor.execute(sql) data = cursor.fetchall()
#fetchall()方法为查询多条数据,fetchone()为查询一条数据 for i in data: if i[0] != None: words = get_key_words(i[0]) print(words)

  在编写过程中出现了这种错误'NoneType' object has no attribute 'split',在网上找了好长时间为什么会出现这样的错误,错误出现在最后通过循环对数据库中的数据进行提取的时候,我通过这种方法,查看了每条数据的类型,发现在第六条数据类型为NoneType,说明第六条数据为空,所以才会报错

for i in data:
    print(type(i[0]))

  

 

 

当遇到为空的数据时候,只要跳过就可以了,所以加了一条判断语句,只有不为空的时候,才执行函数进行关键词提取,最开始使用的是:

for i in data:
     if len(i[0])>0:
     # if i[0] != None:
      words = get_key_words(i[0])
      print(words)

出现了如下的错误:TypeError: object of type 'NoneType' has no len()

这就说明这种判断是否为空的方法是错误的,后发现Nonetype类型,其实就是值为None,所以直接判断值就可以了直接可以用:

if i[0] != None:最后错误解决,成功提取了关键词。

 

posted on 2020-03-14 23:40  啥123  阅读(3481)  评论(0编辑  收藏  举报