簡體   English   中英

在Python中快速搜索單詞列表的字典

[英]Fast dictionary lookup for word list in Python

我正在Python 3中進行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的速度,特別是在word_list大約100個單詞長的情況下。 可能嗎? 可以使用外部庫,例如nltk,spacy,numpy等。

目前,我的筆記本電腦需要花費6us。

>>> %timeit f(mydict, word_list*50)
6.74 us +- 2.77 us per loop (mean +- std. dev. of 7 runs, 100000 loops each)

有多個庫可以處理將字符串/令牌列表轉換為矢量表示形式。

例如,使用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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM