Skip to main content
 首页 » 编程设计

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

2025年05月04日10duanxz

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

 {'me': 41, 'are': 21, 'the': 0} 

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

['I', 'liked', 'the', 'color', 'of', 'this', 'top'] 
['Just', 'grabbed', 'this', 'today', 'great', 'find'] 

我如何将这些单词中的每一个编码成它们在字典中的对应值。例如:

[56, 78, 5, 1197, 556, 991, 40]  

请您参考如下方法:

干什么

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] 

如果您希望将 'Just' 和 'just' 映射到相同的对象,则可能需要使用 x.lower()值(value)。