如何在Python中对列表中的单词进行编码

Jai*_*tia 1 python encoding text-processing dictionary dataframe

我有一个字典,其中我将每个单词作为键和相应的整数值,例如:

 {'me': 41, 'are': 21, 'the': 0}
Run Code Online (Sandbox Code Playgroud)

我有一个数据框,其中包含一列已经标记化的单词列表,例如:

['I', 'liked', 'the', 'color', 'of', 'this', 'top']
['Just', 'grabbed', 'this', 'today', 'great', 'find']
Run Code Online (Sandbox Code Playgroud)

如何将这些单词中的每个单词编码为字典中的相应值.例如:

[56, 78, 5, 1197, 556, 991, 40] 
Run Code Online (Sandbox Code Playgroud)

BiB*_*iBi 5

做什么

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]
Run Code Online (Sandbox Code Playgroud)

你可能想使用x.lower(),如果你想'Just''just'映射到相同的值.