2013-12-08 75 views
3

我想使用Python 2.7和Levenshtein函數將姓氏列表匹配到全名列表。爲了減少工作量,我只在第一個字母相同的情況下才會匹配(儘管這在性能上似乎沒有太大區別)。如果找到匹配項,則從全名中刪除匹配的詞(以使後續的名字匹配更容易)。這兩個列表都包含幾萬個條目,所以我的解決方案相當慢。我如何在不解析完整名稱的情況下加快速度? 這裏是我迄今爲止(對於情況下,我省略了一些,如果條件在lastnames由若干字):Python,嵌套循環,匹配和性能

import Levenshtein 

listoflastnames=(['Jones', 'Sallah']) 
listoffullnames=(['Henry', 'Jones', 'Junior'],['Indiana', 'Jones']) 


def match_strings(lastname, listofnames): 
    match=0 
    matchedidx=[] 
     for index, nameelement in enumerate(listofnames):   
      if lastname[0]==nameelement [0]: 
       if Levenshtein.distance(nameelement, lastname)<2: 
        matchedidx.append(index) 
        match=match+1 
    if match==1: 
     newnamelist = [i for j, i in enumerate(listofnames) if j not in matchedidx] 
    return 1, newnamelist 
return 0, listofnames 



for x in listoflastnames: 
    for y in listoffullnames: 
     match, newlistofnames=match_strings(x,y) 
     if match==1: 
      #go to first name match... 

任何幫助,將不勝感激!

更新:在此期間,我使用了多處理模塊讓我的所有4核處理問題而不僅僅是一個,但匹配仍需要很長時間。

+0

'Levenshtein.distance(G,publastnames [0]' 什麼是G和publastnames [0]這裏? – M4rtini

+0

對不起,那是一個遺留的從舊版本。在萊文斯坦功能比較姓和一個字 – MrFancypants

+1

如果只打算執行第一個字母相同的計算,則可能需要將列表拆分爲第一個字母索引的字典,然後您可以執行只有可行的候選人之間進行比較,而不是所有人之間的比較,這是否會提高性能取決於花在這個開銷上的時間是多少,而不是距離計算的結果 – DSM

回答

1

這簡化了match_string函數中的for循環,但在我的測試中並沒有顯着提高速度。最大的損失是在帶有姓氏和全名的兩個for循環中。

def match_strings(lastname, listofnames): 
    firstCaseMatched = [name for name in listofnames if lastname[0] == name[0]] 
    if len(firstCaseMatched): 
     matchedidx = [index for index, ame in enumerate(firstCaseMatched) if Levenshtein.distance(lastname, name) < 2] 
     match = len(matchedidx) 
    else: 
     match = 0 
    if match == 1: 
     newnamelist = [i for j, i in enumerate(listofnames) if j not in matchedidx] 
     return 1, newnamelist 
    return 0, listofnames 

您可能需要進行排序知姓氏的名單,他們分成dict每個起始字符。然後將名稱列表中的每個名稱與該名稱進行匹配。

假設全名列表始終具有作爲第一個元素的名字。您可以將比較限制爲僅限其他元素。

+0

感謝您的所有建議。我已經把姓氏分成一個字典,其中第一個字母是建議的鍵。與多處理一起,該腳本現在的速度是原始版本的20倍。 – MrFancypants

+0

順便說一句,我假設你使用Levenshtein距離,因爲名稱可能拼寫錯誤?你能確定名字中的第一個字母是正確的嗎? – M4rtini

+0

我無法確定,但是當我測試腳本時未排除第一個字母與我的數據子集相匹配的情況時,似乎引入了大量誤報。因爲我必須從結果集中手動刪除誤報,所以我願意接受略低的召回率:) – MrFancypants