Python中词表的快速词典查找

2024-06-17 13:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python3中使用NLP,并试图优化代码的速度。 代码使用给定的字典将单词列表转换为数字列表(或数组)。在

例如

mydict = {'hello': 0, 'world': 1, 'this': 2, 'is': 3, 'an': 4, 'example': 5}
word_list = ['hello', 'world']

def f(mydict, word_list):
    return [mydict[w] for w in word_list]

# f(mydict, word_list) == [1, 2]

我想加快函数f的速度,尤其是当单词表大约有100个单词时。有可能吗?可以使用诸如nltk、spacy、numpy等外部库。在

目前,我的笔记本电脑需要6个我们。在

^{2}$

Tags: 代码hello列表world字典nlp数字数组
1条回答
网友
1楼 · 发布于 2024-06-17 13:31:45

有多个库来处理将字符串/令牌列表转换为向量表示。在

例如,使用gensim

>>> import gensim
>>> from gensim.corpora import Dictionary
>>> documents = [['hello', 'world'], ['NLP', 'is', 'awesome']]
>>> dict = Dictionary(documents)

# This is not necessary, but if you need to debug
# the word and attached indices, you can do:

>>> {idx:dict[idx]for idx in dict}
{0: 'hello', 1: 'world', 2: 'NLP', 3: 'awesome', 4: 'is'}

# To get the indices of the words per document, e.g.
>>> dict.doc2idx('hello world'.split())
[0, 1]
>>> dict.doc2idx('hello world is awesome'.split())
[0, 1, 4, 3]

相关问题 更多 >