python 文本聚类

简介: 读取excel excel 格式 excel.py # -*- coding: utf-8 -*-import xdrlib ,sysimport xlrdimport jsondef open_excel(file= '/home/lhy/data/data.xlsx'): try: data = xlrd.open_workboo

读取excel

excel 格式



excel.py

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

import  xdrlib ,sys
import xlrd
import json

def open_excel(file= '/home/lhy/data/data.xlsx'):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception,e:
        print str(e)
#根据索引获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_index:表的索引
def excel_table_byindex(file= '/home/lhy/data/data.xlsx',colnameindex=0,by_index=0):
    data = open_excel(file)
    table = data.sheets()[by_index]
    nrows = table.nrows #行数
    ncols = table.ncols #列数
    colnames =  table.row_values(colnameindex) #某一行数据
    list =[]
    for rownum in range(1,nrows):

         row = table.row_values(rownum)
         if row:
             app = {}
             for i in range(len(colnames)):
                app[colnames[i]] = row[i]
             list.append(app)
    return list

#根据名称获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_name:Sheet1名称
#def excel_table_byname(file= '/home/lhy/data/data.xlsx',colnameindex=0,by_name=u'Sheet1'):
def excel_table_byname(file='/home/lhy/data/data.xlsx', colnameindex=0, by_name=u'word'):
    data = open_excel(file)
    table = data.sheet_by_name(by_name)
    nrows = table.nrows #行数
    colnames =  table.row_values(colnameindex) #某一行数据
    list =[]
    for rownum in range(1,nrows):
         row = table.row_values(rownum)
         if row:
             app = {}
             for i in range(len(colnames)):
                app[colnames[i]] = row[i]
             list.append(app)
    return list

def main():
   tables = excel_table_byindex()
   for row in tables:
       '''print row.decode('utf-8')'''
       wenti=row[u'问题']
      # wenti=wenti[1:len(wenti)-1]
       print json.dumps(wenti, encoding="UTF-8", ensure_ascii=False)
       #print type(row)

 #  tables = excel_table_byname()
  # for row in tables:
   #    print row

if __name__=="__main__":
    main()

分词

TextFenci.py

# -*- coding: UTF-8 -*-
import jieba.posseg as pseg
import excel
import json
def getWordXL():
     #words=pseg.cut("对这句话进行分词")
     list=excel.excel_table_byindex();
     aList = []
     for index in range(len(list)):
          wenti = list[index][u'问题']
          words = pseg.cut(wenti)
          word_str=""
          for key in words:
               #aList.insert()import json
              # print type(key)
               word_str=word_str+key.word+" "
              # print key.word,"  ",
          aList.insert(index,word_str)
     return aList,list  #第一个参数为分词结果,第儿歌参数为原始文档

def main():
     aList=getWordXL()
     print "1234"
     print json.dumps(aList, encoding="UTF-8", ensure_ascii=False)

if __name__=="__main__":
    main()

TF_IDF 权重生成

TF_IDF.py

# -*- coding: UTF-8 -*-
import jieba.posseg as pseg
import excel
import json
def getWordXL():
     #words=pseg.cut("对这句话进行分词")
     list=excel.excel_table_byindex();
     aList = []
     for index in range(len(list)):
          wenti = list[index][u'问题']
          words = pseg.cut(wenti)
          word_str=""
          for key in words:
               #aList.insert()import json
              # print type(key)
               word_str=word_str+key.word+" "
              # print key.word,"  ",
          aList.insert(index,word_str)
     return aList,list  #第一个参数为分词结果,第儿歌参数为原始文档

def main():
     aList=getWordXL()
     print "1234"
     print json.dumps(aList, encoding="UTF-8", ensure_ascii=False)

if __name__=="__main__":
    main()

k-means 聚类

KMeans.py

# -*- coding: utf-8 -*-
from sklearn.cluster import KMeans
import TF_IDF
import json,sys
reload(sys)
sys.setdefaultencoding('utf-8')
weight, textList = TF_IDF.getTFIDF()
def getCU(leibieNum):
    LEIBI=leibieNum    #100个类别
    #print "####################Start Kmeans:分成"+str(LEIBI)+"个类"

    clf = KMeans(n_clusters=LEIBI)

    s = clf.fit(weight)
    #print s

    # 20个中心点
    #print(clf.cluster_centers_)

    # 每个样本所属的簇
    #print(clf.labels_)
    i = 1
    textFencuList=[]
    for i in range(0,LEIBI):
        textFencu2=[]
        textFencuList.append(textFencu2)
    for i in range(len(clf.labels_)):
        try:
            textFencuList[clf.labels_[i - 1]].append(textList[i])
        except Exception, e:
            print "#######错误:"+str(clf.labels_[i - 1])+"  "+str(i)
    fo = open("/home/lhy/data/wbjl.txt", "wb")
    for index in range(len(textFencuList)):
        fo.write("\n#############################第"+str(index)+"个分类##################\n");  # 写入文件
        print ""
        print "#############################第"+str(index)+"个分类##################";
        print ""
        for ab in textFencuList[index]:
            thisword=json.dumps(ab, encoding="UTF-8", ensure_ascii=False)
            #thisword = json.dumps(ab)
            fo.write(thisword + "\n")  # 写入文件
            print thisword
    fo.close();
        # 用来评估簇的个数是否合适,距离越小说明簇分的越好,选取临界点的簇个数
    print("############评估因子大小,用来评估簇的个数是否合适,距离越小说明簇分的越好,选取临界点的簇个数:类别"+str(LEIBI)+"    因子"+str(clf.inertia_))
getCU(300)
'''for index in range(100,1000,10):
    getCU(index)
    '''


目录
相关文章
|
2月前
|
Python
python 找到并去除文本中的全部链接
这篇文章提供了一个使用Python正则表达式找到并删除文本中所有链接的代码示例。
|
2月前
|
机器学习/深度学习 数据采集 数据可视化
【python】python当当数据分析可视化聚类支持向量机预测(源码+数据集+论文)【独一无二】
【python】python当当数据分析可视化聚类支持向量机预测(源码+数据集+论文)【独一无二】
|
6天前
|
自然语言处理 算法 数据挖掘
探讨如何利用Python中的NLP工具,从被动收集到主动分析文本数据的过程
【10月更文挑战第11天】本文介绍了自然语言处理(NLP)在文本分析中的应用,从被动收集到主动分析的过程。通过Python代码示例,详细展示了文本预处理、特征提取、情感分析和主题建模等关键技术,帮助读者理解如何有效利用NLP工具进行文本数据分析。
25 2
|
15天前
|
机器学习/深度学习 自然语言处理 大数据
使用Python进行文本情感分析
【10月更文挑战第2天】使用Python进行文本情感分析
20 3
|
29天前
|
Linux 开发者 iOS开发
Python中使用Colorama库输出彩色文本
Python中使用Colorama库输出彩色文本
|
1月前
|
XML 数据格式 Python
Python技巧:将HTML实体代码转换为文本的方法
在选择方法时,考虑到实际的应用场景和需求是很重要的。通常,使用标准库的 `html`模块就足以满足大多数基本需求。对于复杂的HTML文档处理,则可能需要 `BeautifulSoup`。而在特殊场合,或者为了最大限度的控制和定制化,可以考虑正则表达式。
35 12
|
1月前
|
机器学习/深度学习 自然语言处理 算法
使用Python实现简单的文本情感分析
【9月更文挑战第13天】本文将介绍如何使用Python编程语言进行基础的文本情感分析。我们将通过一个简单的例子,展示如何利用自然语言处理库nltk和机器学习库sklearn来实现对文本数据的情感倾向性判断。文章旨在为初学者提供一个入门级的指导,帮助他们理解并实践文本情感分析的基本步骤和方法。
28 6
|
1月前
|
机器学习/深度学习 存储 人工智能
文本情感识别分析系统Python+SVM分类算法+机器学习人工智能+计算机毕业设计
使用Python作为开发语言,基于文本数据集(一个积极的xls文本格式和一个消极的xls文本格式文件),使用Word2vec对文本进行处理。通过支持向量机SVM算法训练情绪分类模型。实现对文本消极情感和文本积极情感的识别。并基于Django框架开发网页平台实现对用户的可视化操作和数据存储。
37 0
文本情感识别分析系统Python+SVM分类算法+机器学习人工智能+计算机毕业设计
|
1月前
|
Python
在Python中,文本查找和替换的常用操作
在Python中,文本查找和替换的常用操作,使用字符串方法进行查找和替换,使用正则表达式进行查找和替换,对所查找到的内容进行计数。
26 1
|
2月前
|
机器学习/深度学习 人工智能 自然语言处理
【自然语言处理】python之人工智能应用篇——文本生成技术
文本生成是指使用自然语言处理技术,基于给定的上下文或主题自动生成人类可读的文本。这种技术可以应用于各种领域,如自动写作、聊天机器人、新闻生成、广告文案创作等。
65 8