Reputation: 176
I have a dictionary where I have each word as a key and a corresponding integer value, such as :
{'me': 41, 'are': 21, 'the': 0}
I have a data frame with a column of lists of words that are already tokenized, such as :
['I', 'liked', 'the', 'color', 'of', 'this', 'top']
['Just', 'grabbed', 'this', 'today', 'great', 'find']
How can I encode each of these words into their corresponding values from the dictionary. For example:
[56, 78, 5, 1197, 556, 991, 40]
Upvotes: 1
Views: 1678
Reputation: 14313
The following uses a dictionary (final_dictionary
) to determine the id's of the words. This is great if you have a preset dictionary of id's.
def encode_tokens(tokens):
encoded_tokens = tokens[:]
for i, token in enumerate(tokens):
if token in final_dictionary:
encoded_tokens[i] = final_dictionary[token]
return encoded_tokens
print(encode_tokens(tokens))
If you are dynamically assigning id's I would implement a class to do so (see bellow). If you, however, have a dictionary of id's that you have already defined ahead of time, you can pass in the keyword argument di
:
token_words_1 = ['I', 'liked', 'the', 'color', 'of', 'this', 'top']
token_words_2 = ['I', 'liked', 'to', 'test', 'repeat', 'words']
class AutoId:
def __init__(self, **kwargs):
self.di = kwargs.get("di", {})
self.loc = 0
def get(self, value):
if value not in self.di:
self.di[value] = self.loc
self.loc += 1
return self.di[value]
def get_list(self, li):
return [*map(self.get, li)]
encoding = AutoId()
print(encoding.get_list(token_words_1))
print(encoding.get_list(token_words_2))
Upvotes: 1
Reputation: 2774
from itertools import chain
import numpy as np
# d = {'me': 41, 'are': 21, 'the': 0}
l1 = ['I', 'liked', 'the', 'color', 'of', 'this', 'top']
l2 = ['Just', 'grabbed', 'this', 'today', 'great', 'find']
# This is just for data generation for the sake of a complete example.
# Use your already given d here instead.
d = {k: np.random.randint(10) for k in chain(l1, l2)}
print(d)
l1_d = [d.get(k, 0) for k in l1] # <- this is the actual command you need
print(l1_d)
l2_d = [d.get(k, 0) for k in l2]
print(l2_d)
Outcome:
{'I': 3, 'liked': 3, 'the': 8, 'color': 7, 'of': 3, 'this': 5,
'top': 3, 'Just': 6, 'grabbed': 0, 'today': 0, 'great': 7, 'find': 0}
[3, 3, 8, 7, 3, 5, 3]
[6, 0, 5, 0, 7, 0]
Upvotes: 1
Reputation: 7908
What about doing
word2key = {'me': 41, 'are': 21, 'the': 0}
words = ['Just', 'grabbed', 'this', 'today', 'great', 'find']
default = 'unknown'
output = [word2key.get(x, default) for x in words]
You might want to use x.lower()
if you want 'Just'
and 'just'
to be mapped to the same value.
Upvotes: 5
Reputation: 3720
Assume your dict is in a variable named d
and your list is named l
:
d = {'me': 41, 'are': 21, 'the': 0}
l = ['I', 'liked', 'the', 'color', 'of', 'this', 'top']
print(l)
c = 0
while c < len(l):
try:
l[c] = d[l[c]]
except:
l[c] = None
c += 1
print(l)
Upvotes: 1