EmoTFIDF 1.2.6__tar.gz → 1.2.7__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- EmoTFIDF-1.2.7/EmoTFIDF/EmoTFIDF.py +168 -0
- EmoTFIDF-1.2.7/EmoTFIDF/emotions_lex.json +50575 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/EmoTFIDF.egg-info/PKG-INFO +2 -2
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/EmoTFIDF.egg-info/SOURCES.txt +3 -0
- EmoTFIDF-1.2.7/EmoTFIDF.egg-info/requires.txt +3 -0
- EmoTFIDF-1.2.7/EmoTFIDF.egg-info/top_level.txt +2 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/PKG-INFO +2 -2
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/setup.py +6 -10
- EmoTFIDF-1.2.7/tests/__init__.py +3 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/tests/test_emotfidf.py +1 -1
- EmoTFIDF-1.2.6/EmoTFIDF.egg-info/requires.txt +0 -1
- EmoTFIDF-1.2.6/EmoTFIDF.egg-info/top_level.txt +0 -2
- {EmoTFIDF-1.2.6/tests → EmoTFIDF-1.2.7/EmoTFIDF}/__init__.py +0 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/EmoTFIDF.egg-info/dependency_links.txt +0 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/LICENSE +0 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/README.md +0 -0
- {EmoTFIDF-1.2.6 → EmoTFIDF-1.2.7}/setup.cfg +0 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
3
|
+
from collections import Counter
|
|
4
|
+
import string
|
|
5
|
+
import nltk
|
|
6
|
+
from nltk.corpus import stopwords
|
|
7
|
+
import urllib.request
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
nltk.download('wordnet')
|
|
11
|
+
nltk.download('punkt')
|
|
12
|
+
nltk.download('stopwords')
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def process_message(message):
|
|
16
|
+
"""
|
|
17
|
+
Process a text message by tokenizing, removing stop words, numbers, small words, and punctuation.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
message (str): The input text message to process.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
str: The processed text message.
|
|
24
|
+
"""
|
|
25
|
+
words = nltk.word_tokenize(message.lower())
|
|
26
|
+
words = [w for w in words if len(w) > 3] # remove small words
|
|
27
|
+
sw = stopwords.words('english')
|
|
28
|
+
words = [word for word in words if not word.isnumeric()]
|
|
29
|
+
words = [word for word in words if word not in sw]
|
|
30
|
+
words = [word for word in words if word not in string.punctuation]
|
|
31
|
+
return ' '.join(words)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_emotions(self):
|
|
35
|
+
"""
|
|
36
|
+
Extract emotions from the processed text based on a predefined lexicon.
|
|
37
|
+
|
|
38
|
+
This function updates the following attributes of the EmoTFIDF object:
|
|
39
|
+
- em_list: A list of emotions found in the text.
|
|
40
|
+
- em_dict: A dictionary mapping words to their corresponding emotions.
|
|
41
|
+
- emotion_scores: A frequency count of each emotion found.
|
|
42
|
+
- em_frequencies: The percentage of each emotion relative to the total number of emotions found.
|
|
43
|
+
"""
|
|
44
|
+
em_list = []
|
|
45
|
+
em_dict = dict()
|
|
46
|
+
em_frequencies = Counter()
|
|
47
|
+
lexicon_keys = self.lexicon.keys()
|
|
48
|
+
for word in self.words:
|
|
49
|
+
if word in lexicon_keys:
|
|
50
|
+
if isinstance(self.lexicon[word], list):
|
|
51
|
+
emotions_found = list(set(self.lexicon[word]))
|
|
52
|
+
emotions_found = list(filter(None, emotions_found))
|
|
53
|
+
if emotions_found is not None:
|
|
54
|
+
if 'negative' in emotions_found:
|
|
55
|
+
emotions_found.remove('negative')
|
|
56
|
+
elif 'positive' in emotions_found:
|
|
57
|
+
emotions_found.remove('positive')
|
|
58
|
+
em_list.extend(emotions_found)
|
|
59
|
+
em_dict.update({word: self.lexicon[word]})
|
|
60
|
+
for word in em_list:
|
|
61
|
+
em_frequencies[word] += 1
|
|
62
|
+
sum_values = sum(em_frequencies.values())
|
|
63
|
+
em_percent = {'fear': 0.0, 'anger': 0.0, 'anticipation': 0.0, 'trust': 0.0, 'surprise': 0.0,
|
|
64
|
+
'sadness': 0.0, 'disgust': 0.0, 'joy': 0.0}
|
|
65
|
+
for key in em_frequencies.keys():
|
|
66
|
+
em_percent.update({key: float(em_frequencies[key]) / float(sum_values)})
|
|
67
|
+
self.em_list = em_list
|
|
68
|
+
self.em_dict = em_dict
|
|
69
|
+
self.emotion_scores = dict(em_frequencies)
|
|
70
|
+
self.em_frequencies = em_percent
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class EmoTFIDF:
|
|
74
|
+
"""
|
|
75
|
+
A class to process text, extract emotions using a lexicon, and compute TF-IDF scores for words.
|
|
76
|
+
|
|
77
|
+
Attributes:
|
|
78
|
+
lexicon (dict): A dictionary containing words as keys and corresponding emotions as values.
|
|
79
|
+
"""
|
|
80
|
+
with urllib.request.urlopen("https://raw.githubusercontent.com/mmsa/EmoTFIDF/main/EmoTFIDF/emotions_lex.json") as url:
|
|
81
|
+
lexicon = json.loads(url.read().decode())
|
|
82
|
+
|
|
83
|
+
def set_text(self, text):
|
|
84
|
+
"""
|
|
85
|
+
Set and process the input text for emotion extraction and TF-IDF computation.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
text (str): The input text to process.
|
|
89
|
+
"""
|
|
90
|
+
self.text = process_message(text)
|
|
91
|
+
self.words = list(nltk.word_tokenize(self.text))
|
|
92
|
+
self.sentences = list(nltk.sent_tokenize(self.text))
|
|
93
|
+
get_emotions(self)
|
|
94
|
+
|
|
95
|
+
def set_lexicon_path(self, path):
|
|
96
|
+
"""
|
|
97
|
+
Set the path to a custom lexicon file.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
path (str): The file path to the custom lexicon in JSON format.
|
|
101
|
+
"""
|
|
102
|
+
self.path = path
|
|
103
|
+
if path and path.strip():
|
|
104
|
+
with open(path) as jsonfile:
|
|
105
|
+
self.lexicon = json.load(jsonfile)
|
|
106
|
+
else:
|
|
107
|
+
with urllib.request.urlopen(
|
|
108
|
+
"https://raw.githubusercontent.com/mmsa/EmoTFIDF/main/emotions_lex.json") as url:
|
|
109
|
+
self.lexicon = json.loads(url.read().decode())
|
|
110
|
+
|
|
111
|
+
def compute_tfidf(self, docs):
|
|
112
|
+
"""
|
|
113
|
+
Compute TF-IDF scores for a collection of documents.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
docs (list of str): A list of documents to process.
|
|
117
|
+
|
|
118
|
+
Updates:
|
|
119
|
+
self.tfid (pd.DataFrame): A DataFrame containing TF-IDF scores for the documents.
|
|
120
|
+
self.vectorizer (TfidfVectorizer): The TF-IDF vectorizer used for computation.
|
|
121
|
+
self.feature_names (list of str): The feature names (terms) used in the TF-IDF vectorizer.
|
|
122
|
+
"""
|
|
123
|
+
stop_words = stopwords.words('english')
|
|
124
|
+
vectorizer = TfidfVectorizer(max_features=200, stop_words=stop_words, token_pattern=r'(?u)\b[A-Za-z]+\b')
|
|
125
|
+
vectors = vectorizer.fit_transform(docs)
|
|
126
|
+
feature_names = vectorizer.get_feature_names_out()
|
|
127
|
+
dense = vectors.todense()
|
|
128
|
+
denselist = dense.tolist()
|
|
129
|
+
df = pd.DataFrame(denselist, columns=feature_names)
|
|
130
|
+
self.tfid = df
|
|
131
|
+
self.vectorizer = vectorizer
|
|
132
|
+
self.feature_names = feature_names
|
|
133
|
+
|
|
134
|
+
def get_ifidf_for_words(self):
|
|
135
|
+
"""
|
|
136
|
+
Compute TF-IDF scores for words in the processed text.
|
|
137
|
+
|
|
138
|
+
Updates:
|
|
139
|
+
self.ifidf_for_words (dict): A dictionary mapping words to their TF-IDF scores.
|
|
140
|
+
"""
|
|
141
|
+
tfidf_matrix = self.vectorizer.transform([self.text]).todense()
|
|
142
|
+
feature_index = tfidf_matrix[0, :].nonzero()[1]
|
|
143
|
+
tfidf_scores = zip([self.feature_names[i] for i in feature_index], [tfidf_matrix[0, x] for x in feature_index])
|
|
144
|
+
self.ifidf_for_words = dict(tfidf_scores)
|
|
145
|
+
|
|
146
|
+
def get_emotfidf(self):
|
|
147
|
+
"""
|
|
148
|
+
Compute emotion scores factorized by TF-IDF weights.
|
|
149
|
+
|
|
150
|
+
Updates:
|
|
151
|
+
self.em_tfidf (dict): A dictionary containing the TF-IDF weighted emotion scores.
|
|
152
|
+
"""
|
|
153
|
+
self.get_ifidf_for_words()
|
|
154
|
+
em_percent = {'fear': 0.0, 'anger': 0.0, 'anticipation': 0.0, 'trust': 0.0, 'surprise': 0.0,
|
|
155
|
+
'sadness': 0.0, 'disgust': 0.0, 'joy': 0.0}
|
|
156
|
+
em_frequencies = Counter()
|
|
157
|
+
for word in self.em_list:
|
|
158
|
+
em_frequencies[word] += 1
|
|
159
|
+
for e in self.em_dict.keys():
|
|
160
|
+
if e in self.ifidf_for_words:
|
|
161
|
+
tfidf_weight = self.ifidf_for_words[e]
|
|
162
|
+
for a in self.em_dict[e]:
|
|
163
|
+
new_fre = round(em_frequencies[a] / tfidf_weight, 2)
|
|
164
|
+
em_frequencies[a] = new_fre
|
|
165
|
+
sum_values = sum(em_frequencies.values())
|
|
166
|
+
for key in em_frequencies.keys():
|
|
167
|
+
em_percent.update({key: round(float(em_frequencies[key]) / float(sum_values), 3)})
|
|
168
|
+
self.em_tfidf = em_percent
|