文本数据预处理
毕业试验数据的要求被迫学习python处理数据
文本预处理一般包括分词、词形归一化、删除停用词。
中文分词没有明确的分割符,英文中以空格分词:
安装Anaconda
个人环境:windows7+python3.8+Anaconda4.3.30版本
安装ntlk库
##安装nltk并测试是否成功
import nltk
nltk.download()
##测试
from nltk.corpus import brown
brown.words()
使用命令安装:
conda install ntlk
查看安装是否成功:
conda list
安装jieba分词库
使用命令安装:
conda install jieba
如果出现错误,使用以下命令:
pip install jieba
打开jupyter notebook
创建python文件,测试结巴分词:
import jieba
sentence = '谁都不要说抱歉'
term_list = jieba.cut(sentence,cut_all=True)
print('全模式分词:'+'/'.join(term_list))
词性标注:
ntlk中词性标注:
归一化处理:
英文中单词的变种词汇,例如一个单词可以是一般现在时,过去式和将来时等,在信息检索和文本挖掘时,需要对一个词的不同形态进行规范化,以提高文本的处理效率。一般分为词干提取和词形还原。目前有波特词干提取器和拉卡斯特词干提取器,NLTK库中有一个强大的还原模块,使用WordNetLemmatizer类来获取根词。
词形还原是去除词缀以获得单词的基本形式,称之为根词,存在于字典,不同于词干,词干不一定是标准的单词,也可能不存在与词典中,获取单词的基本形式的方法是lemmatize()
使用波特词干提取器将单词还原词形
from nltk.stem.porter import PorterStemmer
porter_obj = PorterStemmer()
porter_obj.stem('watched')
##结果是watch
使用兰卡斯特提取器将单词还原
from nltk.stem.lancaster import LancasterStemmer
lan_obj = LancasterStemmer()
lan_obj.stem('watching')
###结果是watch
使用Snow提取器
from nltk.stem import SnowballStemmer
snow_obj = SnowballStemmer("english")
snow_obj.stem('listened')
##结果是listen
使用wordNet还原词形
from nltk.stem import WordNetLemmatizer
word_obj = WordNetLemmatizer()
word_obj.lemmatize("books")
###book
但是对于多词形的词汇需要传入参数:例如went
word_obj.lemmatize("went")
##结果还是went
##传入参数将其还原
word_obj.lemmatize("went",pos = 'v')
##结果为go
word_obj.lemmatize("did",pos = 'v')
##结果为do
停用词处理
文本中包含有大量的停用词,作为文本分析对于停用词多的文本处理结果可能会导致结果偏差较大,因此需要将文本中的停用词去除,停用词一般是人工产生的,因此需要自己去寻找一些停用词表
##导入停用词包
from nltk.corpus import stopwords
##定义语句
text = 'I hope I am not chosen,but loved.'
##不使用停用词进行分词
words = nltk.word_tokenize(text)
##获取停用词
stop_words = stopwords.words('english')
##去除停用词
remain_list = []
for word in words:
if word not in stop_words:
remain_list.append(word)
print(remain_list)
文本情感分类:
大致分为两种分类:基于情感词典和基于机器学习
情感词典:
1.对文本进行分词操作,从中找出情感词、否定词以及程度副词
2.判断每个情感之前是否有否定词及程度副词,将它之前的否定词和程度副词划分为一组
3.将所有组的得分加起来,得分大于0的归于正向,小于0的归于负向
基于机器学习的方式
朴素贝叶斯思想:
对于给出的待分类项,求解在此项出现的条件下各个类别出现的概率,哪个最大,就认为此待分类项属于哪个类别
nltk.classify模块中的NaiveBayesClassifiler类实现了朴素贝叶斯分类算法,该类中有一个类方法train()用于训练集来训练模型
train(cls,labeled_featuresets,estimator = ELEProbDist)
labeled_featuresets 表示分类的特征集列表
文本情感分类的测试:
import nltk # 导入nlek库
from nltk.corpus import brown # 导入brown模块
import jieba # 导入结巴分词库
from nltk.stem import WordNetLemmatizer # 导入词形还原库
from nltk.corpus import stopwords # 导入停用词
##准备训练的数据
text_one = "This is wonderful book"
text_two = "I like reading this book very much"
text_three = "This book reads well."
text_four = "This book is not good"
text_five = "This is a very bad book."
# 导入贝叶斯分类器
from nltk.classify import NaiveBayesClassifier
# 定义用作分类的函数
def pret_text(text):
# 文本预处理
words = nltk.word_tokenize(text)
wordnet = WordNetLemmatizer()
words = [wordnet.lemmatize(word) for word in words]
# 删除停用词操作
remain_list = [word for word in words if word not in stopwords.words("english")]
print(remain_list)
## 遍历得到对应的词是否在文本中
return {word: True for word in remain_list}
# 测试函数
pret_text(text_one)
#构建训练文本,自定义训练集文本情感编码
train_data = [[pret_text(text_one),1],[pret_text(text_two),1],[pret_text(text_three),1],[pret_text(text_four),-1],[pret_text(text_five),-1]]
#得到训练模型
model = NaiveBayesClassifier.train(train_data)
#模型测试1 结果为1,表示好评
text_test = "I like this Movie very much"
model.classify(pret_text(text_test))
#模型测试2 结果为-1,表示差评
text_test = "This film is very bad"
model.classify(pret_text(text_test))
文本相似度计算:
import nltk # 导入nlek库
from nltk.corpus import brown # 导入brown模块
import jieba # 导入结巴分词库
from nltk.stem import WordNetLemmatizer # 导入词形还原库
from nltk.corpus import stopwords # 导入停用词
# 文本相似度的计算
from nltk import FreqDist
text1 = "John likes to watch movies"
text2 = "John also likes to watch football games"
all_text = text1+' '+text2
#分词处理
words = nltk.word_tokenize(all_text)
# 创建FreqDist对象,记录每个词出现的频率
freq_dist = FreqDist(words)
most_comman_words = freq_dist.most_common(5)
#找到单词的位置
def find_postion(comman_words):
"""
查找常用单词的位置
"""
result = {}
pos = 0
for word in comman_words:
result[word[0]] = pos
pos+=1
return result
##调用方法
pos_dict = find_postion(most_comman_words)
def text_to_vector(words):
"""
将文本转换成词频向量
"""
freq_vec = [0]*5
# 在常用的单词列表中计算词频
for word in words:
if word in list(pos_dict.keys()):
freq_vec[pos_dict[word]] += 1
return freq_vec
# 向量化
vec1 = text_to_vector(nltk.word_tokenize(text1))
vec2 = text_to_vector(nltk.word_tokenize(text2))
#导入向量计算的包,计算文本相似度
from nltk.cluster.util import cosine_distance
cosine_distance(vec1,vec2)
数据可视化
Matplotlib(Python2D绘图库)、Seaborn(专攻于统计可视化)、Bokeh(交互式绘图库)
常见的图形图标分为柱状图、折线图、条形图(横向柱状)、饼图、散点图箱型图
Matplotlib绘制图形,其使用figure()函数创建画布,该模块默认有一个Figure对象,该对象可以理解为一张空白的画布,用于容纳图表的各种组件。
figure函数中的参数有:
num – 表示图形的编号或名称
figsize –用于设置画布尺寸
facecolor – 用于设置画板的背景颜色
edgecolor –用于显示边框颜色
绘制简单的图像:
#手动绘制画布对象,设置背景颜色
plt.figure(figsize = (20,8),dpi = 100,facecolor = 'gray')
plt.plot([1,2,3],[4,5,6])
plt.show()
使用subplot函数绘制单个子图
subplot()函数会将整个绘图区域等分为nrows*ncols的矩阵区域,从左到右、从上到下的顺序对每一个区域进行编号,依次递增。
subplots()函数绘制创建多个子图
subplots()函数会返回一个元祖,元祖的第一个元素为Figure对象(画布),第二个元素为Axes对象(子图)或Axes对象数组。如果创建的是单个子图,返回的是一个Axes对象,否则返回的是一个Axes对象数组。
简单绘制四个图形:
# 创建四个画布,将随机数绘制在最后一个画布中
fig = plt.figure(figsize=(20,8))
fig.add_subplot(2,2,1)
fig.add_subplot(2,2,2)
fig.add_subplot(2,2,3)
fig.add_subplot(2,2,4)
random_arr = np.random.randn(100)
plt.plot(random_arr)
plt.show()
python的pyplot中的函数有
plt.figure(figsize = (20,8),dpi = 100)
data = np.arange(0,1.1,0.01)
plt.plot(data,data**2,label = 'y=x^2')
plt.plot(data,data**3,label = 'y = x^3')
# 显示中文,加入一下两行代码就可以在绘制ide图片中写入中文字符
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #中文显示
plt.rcParams['axes.unicode_minus'] = False
# 设置标题
plt.title("title 标题")
plt.xlabel("x轴")
plt.ylabel("y轴")
#设置刻度信息
plt.xticks([0,0.5,1.0])
plt.yticks([0,0.6,1.2])
# 设置显示图例说明
plt.legend(loc = 'best')
plt.show()
绘制不同图表的函数
- scatter方法
matplotlib.pyplot.scatter(x,y,s=None,c=None,marker = None,alpha=None,linewidths=None,…,**kwargs)
x,y – 表示x轴和y轴对应的数据
s – 指定点的大小
c – 指定散点图的颜色
marker – 表示绘制的散点类型
alpha – 表示点的透明度,接受0-1之间的小数
2.bar方法
bar(x,height,width,,align=’center’,*kwargs)
x – 表示x轴的数据
height –表示条形的高度
width –表示条形的宽度,默认0.8
color –表示条形的颜色
edgecolor —表示条形边框的颜色
颜色 | 说明 |
---|---|
b(blue) | 蓝色 |
g(green) | 绿色 |
r(red) | 红色 |
c(cyan) | 青色 |
m(magenta) | 品红 |
y(yellow) | 黄色 |
k(black) | 黑色 |
w(white) | 白色 |
标记风格:
绘制直方图:
import numpy as np
arr_random = np.random.randn(100)
import matplotlib.pyplot as plt
# 绘制直方图
plt.hist(arr_random,bins = 8,color = 'g',alpha = 0.8)
plt.show()
散点图
import numpy as np
arr_random = np.random.randn(100)
import matplotlib.pyplot as plt
#散点图 scatter
x = np.arange(51)
y = np.random.rand(51)*10
plt.scatter(x,y)
plt.show()
柱状图:
import numpy as np
arr_random = np.random.randn(100)
import matplotlib.pyplot as plt
# 柱状图 对比两部电影在1 - 5月份的票房收入
x = np.arange(5)
y1 = [np.random.randint(20,60) for _ in range(5)]
y2 = [np.random.randint(20,60) for _ in range(5)]
# 确定柱子的宽度
width = 0.3
plt.bar(x,y1,width = width)
plt.bar(x+width,y2,width = width)
plt.show()
点线图:
data = np.arange(1,3,0.3)
plt.plot(data,color = 'c',marker = 'x',linestyle = "--")
plt.plot(data+1,color = 'r',marker = 'o',linestyle=':')
plt.show()
保存图标使用savefig(),需要在show方法之前进行调用7yuhbn