Python批量读取公司年报并进行情感分析--代码实战
生活随笔
收集整理的這篇文章主要介紹了
Python批量读取公司年报并进行情感分析--代码实战
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
該文章代碼均在jupyter Notebook中運(yùn)行,且已安裝相關(guān)包
import jieba import os import csv# 讀取預(yù)定的情感詞列表 def read_dict(file):text = open(file,encoding='gbk').read()text = text.split('\n')words = [w for w in text if w] # 去除空的內(nèi)容return words# 得到情感詞列表 negs = read_dict(r'C:\Users\qingfeng\Desktop\Python爬蟲與文本分析\Python爬蟲與文本分析\Python爬蟲與文本分析課件(更新)\03-初識文本分析\data\Reports\negative.txt') poss = read_dict(r'C:\Users\qingfeng\Desktop\Python爬蟲與文本分析\Python爬蟲與文本分析\Python爬蟲與文本分析課件(更新)\03-初識文本分析\data\Reports\positive.txt') # print(negs,poss)# 計(jì)算目標(biāo)函數(shù)的情感詞 def senti_count(text):wordlist = jieba.lcut(text) # 將要分析的文本進(jìn)行分詞pos_count = 0for pos in poss:pos_count = pos_count + wordlist.count(pos) # 計(jì)算要分析的文本中累計(jì)含有的正面情感詞匯的數(shù)量neg_count = 0for neg in negs:neg_count = neg_count + wordlist.count(neg) # 計(jì)算要分析的文本中累計(jì)含有的正面情感詞匯的數(shù)量return{'wordnum':len(wordlist),'pos':pos_count,'neg':neg_count}# 新建CSV保存內(nèi)容 csvf = open(r'C:\Users\qingfeng\Desktop\company_senti.csv','w',encoding = 'gbk',newline='') writer = csv.writer(csvf) writer.writerow(('company','year','wordnum','pos','neg'))# 對某一個(gè)txt進(jìn)行情感計(jì)算 # text = open(r'C:\Users\qingfeng\Desktop\Python爬蟲與文本分析\Python爬蟲與文本分析\Python爬蟲與文本分析課件(更新)\03-初識文本分析\data\Reports\reports\青海華鼎2015.txt').read() # senti_count(text)# 通過for循環(huán),批量獲取文件路徑,讀取文件 file_list = os.listdir(r'C:\Users\qingfeng\Desktop\Python爬蟲與文本分析\Python爬蟲與文本分析\Python爬蟲與文本分析課件(更新)\03-初識文本分析\data\Reports\reports') for f in file_list:# python中,如果你的字符串最后一位是斜杠(slash)字符,那么即使字符串前面加了r表示regular的普通字符串,也是無法通過編譯的,也是會導(dǎo)致SyntaxError的。file = 'C:\\Users\\qingfeng\\Desktop\\Python爬蟲與文本分析\\Python爬蟲與文本分析\\Python爬蟲與文本分析課件(更新)\\03-初識文本分析\\data\\Reports\\reports\\' + ftext = open(file,encoding = 'gbk').read()senti_score = senti_count(text) # 這里是詞典格式wordnum = senti_score['wordnum']pos = senti_score['pos']neg = senti_score['neg']company = f[:-8] # 切片year = f[-8:-4] # print(company,year,wordnum,pos,neg)writer.writerow((company,year,wordnum,pos,neg)) csvf.close()總結(jié)
以上是生活随笔為你收集整理的Python批量读取公司年报并进行情感分析--代码实战的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android:关闭软键盘自动弹出的解决
- 下一篇: painter软件下载|Infinite