我在Google云端硬盘中总共存储了100个.db文件。这些文件中的所有行都包含一个文本列,为此,我需要使用vaderSentiment包计算每一行的情感极性得分。
我已经设法对这些.db文件之一进行了此操作,但是我想对目录中的所有其他99个文件重复此计算。另外,我想将每个文件['sentiment_compound_polarity']'列的平均值存储在.csv文件的Google Drive目录中。该文件应该只有两列,每行100行(每个文件1行),其中包含文件名和df ['sentiment_compound_polarity']。mean(),用于存储在'/ content / drive / My Drive / Database中的每个.db文件文件/'。
我设法使一些代码可以工作,该代码可以打印每个文件的平均情感分数,但是我不知道如何将其存储在.csv中(当然,我只能复制/粘贴它,但是我想要知道如何做到)。
import sqlite3
import pandas as pd
from google.colab import drive
from nltk.sentiment.vader import SentimentIntensityAnalyzer
drive.mount('/content/drive')
gdrive = '/content/drive/My Drive/Database Files/'
for db in os.listdir(gdrive):
with sqlite3.connect(os.path.join(gdrive, db)) as conn:
df = pd.read_sql_query(SELECT * FROM table, conn)
df['sentiment_compound_polarity'] = df.text.apply(lambda x: SentimentIntensityAnalyzer().polarity_scores(x)['compound'])
print (df['sentiment_compound_polarity'].mean())
非常感谢您的帮助!
首先,您需要准备一个新的数据框(在for循环之外:]
df = pd.DataFrame(columns=['db','mean'])
然后在循环中添加具有数据库名称和均值的新行:
df = df.append(dict(zip(df.columns,[db, df['sentiment_compound_polarity'].mean()])), ignore_index=True)
然后在代码末尾,将数据框保存到CSV文件:
df.to_csv('means.csv')