情感分析预处理

主体类为:

import numpy as np
import pandas as pd
import re
import jieba
from itertools import chain
from collections import Counter
from pyecharts import options as opts
from pyecharts.charts import WordCloud
import datetime


class Pretreat():
    def __init__(self,path=None,kind="csv",column=None,is_clear=True,count=None,count_pic=None):
        #1.读取数据
        if(kind == "csv"):
            self.data=pd.read_csv(path)
        elif(kind == "excel"):
            self.data=pd.read_excel(path)
        self.is_clear=is_clear
        self.column=column#需要处理的行名称
        self.count=count#计数操作,传入个数即为默认的个数,不传入就不做
        self.count_pic=count_pic#画词云图操作,传入个数为默认个数,不传入不做
        #读停用词
        self.stopwords = set()
        with open('停用词.txt',encoding = 'UTF-8') as f:
            for line in f:
                (self.stopwords).add(line.strip())
    #1.多余字符处理函数和jieba分词
    def clear(self,text):
        pattern = r"[!\"#$%&'()*+,-./:;<=>?@[\\\]^_^{|}~—!,。?、¥…():【】《》‘’“”\s ]+"
        re_obj = re.compile(pattern)
        temp = re_obj.sub("",str(text))#多余字符处理
        return jieba.cut(temp)#结巴分词处理
    def clear_participle(self):
        (self.data).drop_duplicates(inplace=True)#去重处理
        self.data[self.column] = self.data[self.column].apply(self.clear)
    #2.停用词处理
    def remove_stopword(self,words):
        return [word for word in words if word not in self.stopwords]
    def stopword(self):
        if self.is_clear == False:
            pass
        else:
            #去除停用词
            self.data[self.column] = self.data[self.column].apply(self.remove_stopword)
    #3.计数
    def count_all(self):
        if self.count==None or self.count<10:#小于10还是不处理了
            pass
        else:
            li_2d = self.data[self.column].tolist()
            #将二维列表转换为一维
            li_1d = list(chain.from_iterable(li_2d))
            print(f'总词汇量:{len(li_1d)}')
            c = Counter(li_1d)
            print(f'不重复词汇量:{len(c)}')
            self.common = c.most_common()#保存一下这个变量
            print(self.common[:self.count])#打印出前需要个给你看看
    #4.画词云图
    def take_pic(self):
        if self.count_pic==None or self.count_pic<10:
            pass
        else:
            # 数据
            words = self.common[:self.count_pic]
            # 渲染图
            c = (
                WordCloud()
                .add("", words, word_size_range=[20, 100], shape='diamond')  # SymbolType.ROUND_RECT
                .set_global_opts(title_opts=opts.TitleOpts(title='WordCloud词云'))
            )
            # 生成图
            c.render(path=f'词云图\\词云图-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")}.html')
    #主调用函数
    def run(self):
        self.clear_participle()
        self.stopword()
        self.count_all()
        self.take_pic()
        print("所有预处理操作已进行完毕!")
        return self.data

主调用函数为:

from Pretreat_all import Pretreat
import pandas as pd


df_data=pd.read_csv("疫情中山陵.csv")
# print(df_data)
pr=Pretreat(path="南京舆情旅游.csv",kind="csv",column="comment",count=10,count_pic=100)
df_data=pr.run()
print(df_data)

上一篇:代码生成器


下一篇:SQL ADD COLUMN子句简介及实例