簡體   English   中英

在單詞列表python中搜索一組單詞的快速方法

[英]fast way to search for a set of words in a list of words python

我有一組大小為20的固定單詞。我有一個20,000個記錄的大文件,其中每個記錄包含一個字符串,我想查找字符串中是否存在固定集中的任何單詞,以及是否存在字。

s1=set([barely,rarely, hardly])#( actual size 20) 

l2= =["i hardly visit", "i do not visit", "i can barely talk"] #( actual size 20,000)

def get_token_index(token,indx):
    if token in s1:
        return indx
    else:
        return -1


def find_word(text):
    tokens=nltk.word_tokenize(text)
    indexlist=[]
    for i in range(0,len(tokens)):
        indexlist.append(i)
    word_indx=map(get_token_index,tokens,indexlist)    
    for indx in word_indx:
        if indx !=-1:
           # Do Something with tokens[indx]

我想知道是否有更好/更快的方法。

您可以將列表理解與double for循環一起使用:

s1=set(["barely","rarely", "hardly"])

l2 = ["i hardly visit", "i do not visit", "i can barely talk"]

locations = [c for c, b in enumerate(l2) for a in s1 if a in b]

在此示例中,輸出為:

[0, 2]

但是,如果您想要訪問出現某個單詞的索引的方式:

from collections import defaultdict

d = defaultdict(list)

for word in s1:
   for index, sentence in l2:
       if word in sentence:
           d[word].append(index)

這個建議只是消除了一些明顯的低效率,但不會影響解決方案的整體復雜性:

def find_word(text, s1=s1): # micro-optimization, make s1 local
    tokens = nltk.word_tokenize(text)    
    for i, word in in enumerate(tokens):
        if word in s1:
           # Do something with `word` and `i`

本質上,當您真正需要的只是循環體內的條件時,通過使用map會減慢速度。因此,基本上,只是擺脫了get_token_index ,它是過度設計的。

這應該工作:

strings = []
for string in l2:
    words = string.split(' ')
    for s in s1:
        if s in words:
            print "%s at index %d" % (s, words.index(s))

最簡單,效率稍高的方法是使用Python Generator函數

index_tuple = list((l2中s1中i的l2.index(i))

您可以為其計時,並檢查它如何有效地滿足您的要求

暫無
暫無

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

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