将字符串映射到 ASCII 表中位置的整数

Dav*_*sry 5 python string unicode numpy vectorization

我有一个像这样的字符串:

word = 'python'
Run Code Online (Sandbox Code Playgroud)

基于string.ascii_lowercase,我想创建一个新数组,如下所示:

[15, 24, 19, 7, 14, 13]
Run Code Online (Sandbox Code Playgroud)

我对这个问题的解决方案是执行以下操作:

alphabet = {char: i for i, char in enumerate(string.ascii_lowercase)}
indices = [alphabet[char] for char in word]
print(indices)
Run Code Online (Sandbox Code Playgroud)

输出:[15, 24, 19, 7, 14, 13]

但我正在寻找一种更有效的方法,而不使用循环。我怎样才能以矢量化的方式做到这一点?

yat*_*atu 2

一种方法是使用并指定 'U1' dtype 从字符串构建一个数组np.fromiter,转换为整数,并减去 unicode 表中字母表的起始位置,97或者我们可以ord('a')按照 Antoine Dubuis 的建议使用 : :

import numpy as np
word = 'python'
np.fromiter(word, dtype='U1').view(np.uint32) - ord('a')
array([15, 24, 19,  7, 14, 13])
Run Code Online (Sandbox Code Playgroud)