-
Notifications
You must be signed in to change notification settings - Fork 1
/
text_nltk.py
141 lines (114 loc) · 4.57 KB
/
text_nltk.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# -*- coding: utf-8 -*-
"""
The text module extracts words from text using punktuation and word tokenizers,
rejects common stopwords, and lemmatizes each word.
Example:
>>> from text import lemma_tokenize
>>> lemma_tokenize('100% of your donation funds medical care for patients around the world.')
['100', '%', 'donation', 'fund', 'medical', 'care', 'patient', 'around', 'world']
Author: Dirk Neumann
"""
import nltk
import nltk.tokenize
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize.api import StringTokenizer
import numpy as np
import numpy.linalg
import sys
emotion_names = ['happy', 'sad', 'surprised', 'angry', 'fearful', 'disgusted',
'rage', 'vigilance', 'ecstasy', 'admiration', 'terror', 'amazement', 'grief', 'loathing',
'anger', 'anticipation', 'joy', 'trust', 'fear', 'surprise', 'sadness', 'disgust', 'anger',
'annoyance', 'interest', 'serenity', 'acceptance', 'apprehension', 'distraction', 'thoughtful', 'boredom',
'aggressiveness', 'optimism', 'love', 'submission', 'awe', 'disapproval', 'remorse', 'contempt',
'hate']
def empathy(x, model=None):
# emotion_names = ['happy', 'sad', 'surprised', 'angry', 'fearful',
# 'disgusted'] #anger disgust fear joy sadness surprise
d = {}
for a_emotion in emotion_names:
print >>sys.stderr, a_emotion
d[a_emotion] = np.dot(vectors(a_emotion, model=model)[1:], x[
1:]) / numpy.linalg.norm(vectors(a_emotion, model=model)[1:]) / numpy.linalg.norm(x[1:])
return d
def lemma_tokenize(paragraph):
lmtzr = WordNetLemmatizer()
try:
return [lmtzr.lemmatize(word).lower() for sentence in tokenize(paragraph) for word in sentence]
except LookupError:
nltk.download('wordnet')
return [lmtzr.lemmatize(word).lower() for sentence in tokenize(paragraph) for word in sentence]
def mean_vector(paragraph, model=None):
return np.nanmean([vectors(w, model=model) for w in lemma_tokenize(paragraph)], axis=0)
def stopwords():
try:
stop_words = stopwords.stop_words
except AttributeError:
try:
stop_words = nltk.corpus.stopwords.words('english')
except LookupError:
nltk.download('stopwords')
stop_words = nltk.corpus.stopwords.words('english')
stop_words.extend(
['-', ':', '.', '\'', '\',', ',', '#', '/', '@', '.,', '(', ')', 'RT', 'I', 'I''m'])
stopwords.stop_words = stop_words
return stop_words
def tokenize(paragraph):
if not paragraph:
return []
try:
detector = tokenize.detector
except AttributeError:
try:
detector = nltk.data.load('tokenizers/punkt/english.pickle')
except LookupError:
nltk.download('punkt')
detector = nltk.data.load('tokenizers/punkt/english.pickle')
tokenize.detector = detector
return [
[
word
for word in nltk.tokenize.word_tokenize(sentence)
if word not in stopwords()
]
for sentence in detector.tokenize(paragraph.strip())
]
'''
def vectors(x):
try:
v = vectors.vectors
except AttributeError:
from gzip import GzipFile
vectors.vectors = {}
from gensim.models import Word2Vec
m = Word2Vec.load('/mnt/data/text8.model')
for i, word in enumerate(m.vocab):
vectors.vectors[word] = [1, ] + [float(x) for x in m[word][:25]]
v = vectors.vectors
return v[x] if x in v else v.itervalues().next()
'''
def semantic_vector_skip(text, model=None):
words = lemma_tokenize(text)
if len(words) == 0:
return None
return [x for x in np.asarray(np.nanmean([vectors(w, model=model) for w in words], axis=0))]
def vectors(x, model=None):
if not model:
model = 'vectors_50d'
try:
v = vectors.vectors
except AttributeError:
vectors.vectors = {}
try:
v = vectors.vectors[model]
except KeyError:
vectors.vectors[model] = {}
from gzip import GzipFile
# for i, row in enumerate(GzipFile('/mnt/data/GoogleNews-vectors-negative300.txt.gz')):
# if i > 0:
filename = '/mnt/data/%s.txt.gz' % model
print >>sys.stderr, 'Loading %s...' % filename
for row in GzipFile(filename):
vectors.vectors[model][
row.split(' ')[0]] = [1, ] + map(float, row.split(' ')[1:26])
v = vectors.vectors[model]
return v[x] if x in v else ([np.nan, ] * len(vectors('the')))