假设我有两个大的文本字符串,我将它们拆分为单词:
import numpy as np
s1 = 'this is a test test test'
s2 = 'that is another test'
terms1 = np.array(s1.split())
terms2 = np.array(s2.split())
现在 terms1
是 ['this', 'is', 'a', 'test', 'test', 'test']
和 terms2
是 ['that', 'is', 'another', 'test']
。
我现在想为每个唯一的单词分配一个 ID,然后为每个包含相应 ID 的 terms
向量获取一个数组,即 terms1 的公共(public)“词汇表”中的索引
和 terms2
:
vocab = np.unique(np.concatenate((terms1, terms2)))
# yields ['a', 'another', 'is', 'test', 'that', 'this']
ind1 = [np.where(t == vocab)[0][0] for t in terms1]
# yields indices into "vocab": [5, 2, 0, 3, 3, 3]
ind2 = [np.where(t == vocab)[0][0] for t in terms2]
# yields indices into "vocab": [4, 2, 1, 3]
这基本上有效。但是,在 for 循环中使用 np.where
似乎效率低下,我想知道 NumPy 中是否有更好的方法来做这些事情?
最佳答案
使用 np.unique
的 return_inverse
参数,然后使用串联输入的长度拆分返回的逆数组:
In [13]: vocab, inv = np.unique(np.concatenate((terms1, terms2)), return_inverse=True)
In [14]: inv[:len(terms1)]
Out[14]: array([5, 2, 0, 3, 3, 3])
In [15]: inv[len(terms1):]
Out[15]: array([4, 2, 1, 3])
关于python - 使用 NumPy 快速进行 token 到索引的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386742/