Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用NumPy实现令牌到索引的快速转换_Python_Arrays_String_Numpy - Fatal编程技术网

Python 使用NumPy实现令牌到索引的快速转换

Python 使用NumPy实现令牌到索引的快速转换,python,arrays,string,numpy,Python,Arrays,String,Numpy,假设我有两个大的文本字符串,我将它们拆分为单词: 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()) 现在术语1是['this','is','a','test','test','test']而术语2是['this','is','other','test'] 现在,我想

假设我有两个大的文本字符串,我将它们拆分为单词:

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())
现在
术语1
['this','is','a','test','test','test']
术语2
['this','is','other','test']

现在,我想为每个唯一的单词分配一个ID,然后为每个
术语
-向量获取一个数组,该向量包含各自的ID,即
术语1
术语2
的公共“词汇表”中的索引:

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中是否有更好的方法来做这些事情?

您可以使用
广播
一次完成所有比较:

In [23]: np.where(terms1[:, None] == vocab)[1]
Out[23]: array([5, 2, 0, 3, 3, 3])

In [24]: np.where(terms2[:, None] == vocab)[1]
Out[24]: array([4, 2, 1, 3])

使用的
return\u 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])

如果将
vocab
制作为一个列表,则可以使用
index()


这似乎比我的速度测试中的
np.where()
要快,但我不确定大型列表会发生什么。

这有一个缺点,即构造一个可能非常大的中间对象。速度和内存效率不如Warren Weckesser的解决方案,但我也喜欢这种方法!我以前从未使用广播进行比较,但在这些情况下它也非常强大。很好,我不知道
return\u inverse
参数!
vocab_list = list(np.unique(np.concatenate((terms1, terms2))))
ind1 = [vocab_list.index(t) for t in terms1]