python - 使用 NumPy 快速进行 token 到索引的转换

标签 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())

现在 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.uniquereturn_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/

相关文章:

javascript - 创建一个数组,将其转换为 json 并将其传递给 php

C++ 数组和内存位置

string - Flutter如何生成随机字符串

java - 向后打印字符串

Python - 如何填充 mysql 表的输出

Python all([6,7,8,9]) = True。但是 6 = 假

python - cProfile 导入

javascript - JavaScript 关联数组的长度

c - 从 C 中的命令行读取

python - 在模块中的测试文件之间传递 py.test fixture