第二天接触python的"恐代码"小白TTTTTTTTTTT
代码如下:
```
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
inputfile='cs1.xlsx'# -*- coding: utf-8 -*-
outfile='1_.xlsx'
ot='cs1_qu.xlsx'
data=pd.read_excel(inputfile,encoding='utf-8')
data=data.dropna()
wen=list(data['简要病史'])
import jieba
#加载停用词表
import codecs
with codecs.open('stopwords.txt','r') as f:
text=f.read()
stoplists=text.splitlines()
we=[]
ll=[]
text=[]
for i in range(len(wen)):
we.append(wen[i].replace(',',''))
seg_list = jieba.cut(we[i])
ll.append(' '.join(seg_list))
text.append(''.join(list([word for word in ll[i] if word not in stoplists])))
#text去除停用词
#pd.DataFrame(ll).to_excel(ot)
#pd.DataFrame(ll).to_excel(outfile)
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
data_l=wen
vectorizer=CountVectorizer() #该类会将文本中的词语转换为词频矩阵,矩阵元素a[i][j] 表示j词在i类文本下的词频
transformer=TfidfTransformer() #该类会统计每个词语的tf-idf权值
tfidf=transformer.fit_transform(vectorizer.fit_transform(ll))
#第一个fit_transform是计算tf-idf,第二个fit_transform是将文本转为词频矩阵
word=vectorizer.get_feature_names()#获取词袋模型中的所有词语
weight=tfidf.toarray()#将tf-idf矩阵抽取出来,元素a[i][j]表示j词在i类文本中的tf-idf权重
pd.DataFrame(weight).to_excel('TFIDF.xlsx')
pd.DataFrame(word).to_excel('word_tf.xlsx')
```
运行结果: