ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

文本相似性算法(二)-分组及分句热度统计

2020-09-17 18:51:07  阅读:198  来源: 互联网

标签:sheet name 老王 list len 分组 分句 相似性 软件


1. 场景描述

软件老王在上一节介绍到相似性热度统计的4个需求,本次介绍分组及分组分句热度统计(需求1和需求2)。

2. 解决方案

分组热度统计首先根据某列进行分组,然后再对这些句进行热度统计,主要是分组处理,分句仅仅是按照标点符号做了下拆分,在代码说明中可以替换下就可以了。

2.1 完整代码

完整代码,有需要的朋友可以直接拿走,不想看代码介绍的,可以直接拿走执行就行。

import jieba.posseg as pseg
import jieba.analyse
import xlwt  # 写入Excel表的库
import pandas as pd
from gensim import corpora, models, similarities
import re
#停词函数
def StopWordsList(filepath):
    wlst = [w.strip() for w in open(filepath, 'r', encoding='utf8').readlines()]
    return wlst
def str_to_hex(s):
    return ''.join([hex(ord(c)).replace('0x', '') for c in s])
# jieba分词
def seg_sentence(sentence, stop_words):
    stop_flag = ['x', 'c', 'u', 'd', 'p', 't', 'uj', 'f', 'r']
    sentence_seged = pseg.cut(sentence)
    outstr = []
    for word, flag in sentence_seged:
        if word not in stop_words and flag not in stop_flag:
            outstr.append(word)
    return outstr
if __name__ == '__main__':
    # 1 这些是jieba分词的自定义词典,软件老王这里添加的格式行业术语,格式就是文档,一列一个词一行就行了,
    # 这个几个词典软件老王就不上传了,可注释掉。
    jieba.load_userdict("g1.txt")
    jieba.load_userdict("g2.txt")
    jieba.load_userdict("g3.txt")

    # 2 停用词,简单理解就是这次词不分割,这个软件老王找的网上通用的。
    spPath = 'stop.txt'
    stop_words = StopWordsList(spPath)

    # 3 excel处理
    wbk = xlwt.Workbook(encoding='ascii')
    sheet = wbk.add_sheet("软件老王sheet")  # sheet名称
    sheet.write(0, 0, '软件老王1-类别')
    sheet.write(0, 1, '软件老王2-原因')
    sheet.write(0, 2, '软件老王3-统计数量')
    sheet.write(0, 3, '导航-链接到明细sheet表')

    inputfile = '软件老王-source2.xlsx'
    data = pd.read_excel(inputfile)  # 读取数据
    grp1 = data.groupby('类别')
    rcount = 1
    for name, group in grp1:
        print(grp1)
        texts = []
        orig_txt = []
        key_list = []
        name_list = []
        sheet_list = []
        name = name.replace('\n', '').replace('/', '')
        for i in range(len(group)):
            row = group.iloc[i].values
            cell = row[1]
            if cell is None:
                continue
            if not isinstance(cell, str):
                continue
            item = cell.strip('\n\r').split('\t')
            string = item[0]
            if string is None or len(string) == 0:
                continue
            else:
                textstr = seg_sentence(string, stop_words)
                texts.append(textstr)
                orig_txt.append(string)
        # 4 相似性处理
        dictionary = corpora.Dictionary(texts)
        feature_cnt = len(dictionary.token2id.keys())
        corpus = [dictionary.doc2bow(text) for text in texts]
        tfidf = models.LsiModel(corpus)
        index = similarities.SparseMatrixSimilarity(tfidf[corpus], num_features=feature_cnt)
        result_lt = []
        word_dict = {}
        count =0
        for keyword in orig_txt:
            count = count+1
            print('开始执行,第'+ str(count)+'行')
            if keyword in result_lt or keyword is None or len(keyword) == 0:
                continue
            kw_vector = dictionary.doc2bow(seg_sentence(keyword, stop_words))
            sim = index[tfidf[kw_vector]]
            result_list = []
            for i in range(len(sim)):
                if sim[i] > 0.5:
                    if orig_txt[i] in result_lt and orig_txt[i] not in result_list:
                        continue
                    result_list.append(orig_txt[i])
                    result_lt.append(orig_txt[i])
            if len(result_list) >0:
                word_dict[keyword] = len(result_list)
            if len(result_list) >= 1:
                name = name.strip('\n\r').replace('\n', '').replace('/', '').replace(',', '').replace('。', '').replace(
                    '*', '')
                name = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", name)
                sname = name[0:10] + '_' + re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", keyword[0:10])+ '_'\
                        + str(len(result_list)+ len(str_to_hex(keyword))) + str_to_hex(keyword)[-5:]
                sheet_t = wbk.add_sheet(sname)  # Excel单元格名字
                for i in range(len(result_list)):
                    sheet_t.write(i, 0, label=result_list[i])
        # 5 按照热度排序 -软件老王
        with open("rjlw.txt", 'w', encoding='utf-8') as wf2:  # 打开文件
            orderList = list(word_dict.values())
            orderList.sort(reverse=True)
            count = len(orderList)
            for i in range(count):
                for key in word_dict:
                    if word_dict[key] == orderList[i]:
                        key_list.append(key)
                        name_list.append(name)
                        word_dict[key] = 0
            wf2.truncate()
        # 6 写入目标excel
        for i in range(len(key_list)):
            sheet.write(i+rcount, 0, label=name_list[i])
            sheet.write(i+rcount, 1, label=key_list[i])
            sheet.write(i+rcount, 2, label=orderList[i])
            if orderList[i] >= 1:
                shname = name_list[i][0:10] + '_' + re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", key_list[i][0:10]) \
                         + '_'+ str(orderList[i]+ len(str_to_hex(key_list[i])))+ str_to_hex(key_list[i])[-5:]
                link = 'HYPERLINK("#%s!A1";"%s")' % (shname, shname)
                sheet.write(i+rcount, 3, xlwt.Formula(link))
        rcount = rcount + len(key_list)
        key_list = []
        name_list = []
        orderList = []
        texts = []
        orig_txt = []
        sheet_list =[]
    wbk.save('软件老王-target2.xls')  

2.2 代码说明

以上的代码中有很明确的注释就不再一一介绍了,重点说几个。

(1)分组处理跟文本相似性热度统计算法实现(一)-整句热度统计相似,不同的是首先按照某一列做了分组处理,然后进行相似性统计,相似性这块一样,其实不同的主要是excel处理这块的内容。

如果你觉得文章对你有些帮助,欢迎微信搜索「软件老王」第一时间阅读或交流!

(2)excle分组用的是pandas包,python中excel数据分组处理。

(3)关于需求2,分组分句,代码如下:

 for i in range(len(group)):
            row = group.iloc[i].values 
            cell = row[1]
            if cell is None:
                continue
            if not isinstance(cell, str):
                continue
            item = cell.strip('\n\r').split('\t') 
            string = item[0]
            #软件老王,这里按照标点符号对原因进行拆分,然后再进行处理。
            lt = re.split(',|。|!|?', string)
            for t in lt:
                if t is None or t.strip() == '' or len(t.strip()) == 0:
                    continue
                else:
                    textstr = seg_sentence(t, stop_words)
                    texts.append(textstr)
                    orig_txt.append(t)

2.3 效果图

(1)软件老王-source2.xlsx

类别 原因
软件老王1 主机不能加电
软件老王1 有时不能加电
软件老王1 开机加电
软件老王2 自检报错或死机
软件老王2 机器噪音大
软件老王3 噪音问题
软件老王1 噪音太大
软件老王1 噪音噪声
软件老王1 声音太大
软件老王2 声音太大
软件老王3 声音太大

(2)软件老王-target2.xls

软件老王1-类别 软件老王2-原因 软件老王3-统计数量 导航-链接到明细sheet表
软件老王1 主机不能加电 3 软件老王1_主机不能加电_2707535
软件老王1 噪音太大 2 软件老王1_噪音太大_18a5927
软件老王1 声音太大 1 软件老王1_声音太大_17a5927
软件老王2 自检报错或死机 1 软件老王2_自检报错或死机_29b673a
软件老王2 机器噪音大 1 软件老王2_机器噪音大_2135927
软件老王2 声音太大 1 软件老王2_声音太大_17a5927
软件老王3 噪音问题 1 软件老王3_噪音问题_17e9898
软件老王3 声音太大 1 软件老王3_声音太大_17a5927

文本相似性算法(二)-分组及分句热度统计

(3)简单说明

从数据中可以看出来,例如:声音太大,分属三类,首先分类,然后再比对相似性。


欢迎关注公众号「软件老王」,IT技术与相关干货分享,回复关键字获取对应干货,java,送必看的10本“武功秘籍”;图片,送100多万张可商用高清图片;面试,送月薪“20k”的java面试题等。

文本相似性算法(二)-分组及分句热度统计

标签:sheet,name,老王,list,len,分组,分句,相似性,软件
来源: https://blog.51cto.com/14130291/2534782

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有