-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnlp_models.py
93 lines (72 loc) · 2.58 KB
/
nlp_models.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
nltk.download('vader_lexicon')
nltk.download('punkt')
sid = SentimentIntensityAnalyzer()
import spacy
from spacy.tokenizer import Tokenizer
nlp = spacy.load("en_core_web_lg")
tokenizer = Tokenizer(nlp.vocab)
STOP_WORDS = nlp.Defaults.stop_words
import pandas as pd
from nltk.stem import PorterStemmer
ps = PorterStemmer()
def processed_score(data=lyrics):
tokens = []
df = pd.DataFrame(data.split(), columns=['words'])
for doc in tokenizer.pipe(df['words']):
doc_tokens = []
for token in doc:
if (token.is_stop == False) & (token.is_punct == False):
doc_tokens.append(token.text.lower())
tokens.append(doc_tokens)
df['tokens'] = tokens
word_list = sum(list([item for item in df['tokens'] if len(item) != 0]), [])
lyrics_processed = ' '.join(word_list)
scores = sid.polarity_scores(lyrics_processed)
return scores
def stemmed_score(data=lyrics):
""" Processes the text via spacy """
tokens = []
words = []
# Stemming
for word in data.split():
words.append(ps.stem(word))
df = pd.DataFrame(words, columns=['words'])
for doc in tokenizer.pipe(df['words']):
doc_tokens = []
for token in doc:
if (token.is_stop == False) & (token.is_punct == False):
doc_tokens.append(token.text.lower())
tokens.append(doc_tokens)
df['tokens'] = tokens
word_list = sum(list([item for item in df['tokens'] if len(item) != 0]), [])
lyrics_processed = ' '.join(word_list)
scores = sid.polarity_scores(lyrics_processed)
return scores
def get_lemmas(data):
""" Gets lemmas for text """
lemmas = []
doc = nlp(data)
for token in doc:
if ((token.is_stop == False) and (token.is_punct == False)) and (token.pos_!= 'PRON'):
lemmas.append(token.lemma_)
return lemmas
def lemma_score(data=lyrics):
""" Processes the text via spacy """
tokens = []
words = []
# Lemmatization
words = get_lemmas(data)
df = pd.DataFrame(words, columns=['words'])
for doc in tokenizer.pipe(df['words']):
doc_tokens = []
for token in doc:
if (token.is_stop == False) & (token.is_punct == False):
doc_tokens.append(token.text.lower())
tokens.append(doc_tokens)
df['tokens'] = tokens
word_list = sum(list([item for item in df['tokens'] if len(item) != 0]), [])
lyrics_processed = ' '.join(word_list)
scores = sid.polarity_scores(lyrics_processed)
return scores