-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastTextEmbeddings.py
More file actions
32 lines (28 loc) · 857 Bytes
/
FastTextEmbeddings.py
File metadata and controls
32 lines (28 loc) · 857 Bytes
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
from gensim.models import KeyedVectors
import nltk
import numpy as np
import re
model = KeyedVectors.load_word2vec_format('wiki.de.vec')
class FastTextEmbeddings():
def __init__(self, text):
self.text = text
try:
self.tokens = nltk.word_tokenize(text)
except:
self.tokens = None
#print(self.text)
@staticmethod
def _getVectorsOf(tokens):
vectors = []
for token in tokens:
try:
vectors.append(model.get_vector(re.sub('[^A-Za-z0-9]+', '', token).lower()))
except:
#print(token)
pass
return vectors
def getMeanEmbedding(self):
if self.tokens is None:
return None
else:
return np.array(FastTextEmbeddings._getVectorsOf(self.tokens)).mean(axis=0)