-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsentiment_analysis.py
77 lines (66 loc) · 1.51 KB
/
sentiment_analysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from pymongo import MongoClient
import datetime
import numpy as np
import pandas as pd
# connect
cn = MongoClient("localhost")
db = cn.enron_mail
counter = 1
sid = SentimentIntensityAnalyzer()
avg_sent = 0
# loop through all mail items with one recipient
for document in db.messages.find({"recipients":{"$size":1}}):
mail = document["text"]
# remove all text after the "To:" string, hopefully this removes forwarded emails and old emails
#
mail = mail.split("To:")[0]
counter += 1
if counter % 100 == 0:
print(datetime.datetime.utcnow(), counter)
print(avg_sent)
ss = sid.polarity_scores(mail)
avg_sent = (avg_sent + ((ss['compound']-avg_sent)/counter))
db.messages.update_one({
"_id": document["_id"]
}, {
"$set": {
"sentiment": float(ss['compound'])
}
}, upsert=False)
summary = db.messages.aggregate([
{
"$match":{
"recipients":{
"$size":1
}
}
},
{
"$project":{
"_id":0,
"recipients":1,
"sentiment":1
}
},
{
"$unwind":"$recipients"
},
{
"$group":{
"_id":"$recipients",
"avgsent":{
"$avg":"$sentiment"
},
"count":{
"$sum":1
}
}
},
{
"$sort": {"avgsent": 1}
}
])
df = pd.DataFrame(list(summary))
print(df.head())
df.to_csv('sentiment emails.csv')