word_list = []
def main():with open('emotion_word.txt','r',encoding="utf-8") as f:global word_listfor line in f.readlines():word_list.append(line.strip('\n'))with open('tem.txt','a',encoding="utf-8") as f:writted = 'word_list = '+str(word_list)+'\n'f.write(writted)if __name__=='__main__':main()
class EmotionAnalysis:def __init__(self,news=None):self.news = newsself.list = []def __repr__(self):return "News:"+self.news#新聞去標簽,繁->簡def delete_label(self):rule = r'(<.*?>)| |\t|\n|○|■|☉'self.news = re.sub(rule,'',self.news)self.news = cht_to_chs(self.news)#得到成績和方差def get_score(self):self.list = list(jieba.cut(self.news))index_list = zip(range(len(self.list)),self.list)score = 0mean_list = []#tem_list= []for (index,word) in index_list:#tem_list.append(word)tem_score = 0#print("NO:",index,'WORD:',word)if (word in pos_emotion) or (word in pos_envalute):tem_score = 0.1#搜索程度詞if self.list[index-1] in most_degree and (index-1):tem_score = tem_score*3elif self.list[index-1] in very_degree and (index-1):tem_score = tem_score*2.5elif self.list[index-1] in more_degree and (index-1):tem_score = tem_score*2elif self.list[index-1] in ish_degree and (index-1):tem_score = tem_score*1.5elif self.list[index-1] in least_degree and (index-1):tem_score = tem_score*1else:pass#搜索否定詞/反意詞if (self.list[index-1] in neg_degree and index!=0) or (index<len(self.list)-1 and self.list[index+1] in neg_degree):tem_score = -tem_score#print("| tem_score:",tem_score)elif (word in neg_emotion) or (word in neg_envalute):tem_score = -0.3if self.list[index-1] in most_degree and (index-1):tem_score = tem_score*3elif self.list[index-1] in very_degree and (index-1):tem_score = tem_score*2.5elif self.list[index-1] in more_degree and (index-1):tem_score = tem_score*2elif self.list[index-1] in ish_degree and (index-1):tem_score = tem_score*1.5elif self.list[index-1] in least_degree and (index-1):tem_score = tem_score*1else:pass#print("| tem_score:",tem_score)mean_list.append(tem_score)score+=tem_score#print(tem_list)#返回(成績,方差)return (score,np.var(mean_list))
No4.報錯處理
一共231506條新聞,為了方便回查,設置報錯處理(在數據庫操作的類里實現)
log_file = 'error.log'
class SQL(object):......def run(self,cmd,index):try:self.read_SQL(cmd,index)self.operate()self.write_SQL(index)self.w_conn.commit()except Exception as r:self.r_conn.rollback()self.w_conn.rollback()error = "ID "+str(self.r_dict['id'])+str(r)global log_filelog_error(log_file = log_file,error=error)