2017-05-16 351 views
2

建立通過遍歷字符串

使用Scrapy之間的範圍內,我刮房屋的廣告。根據住房廣告,我獲得郵政編碼。

我有一個字典聯郵政編碼到區,

postal_district = {'A': ['1011AB', '1011BD', '1011BG', '1011CE', 
         '1011CH', '1011CZ', '1011DB', '1011DD']} 

整個詞典可以被看作here

列表中的每兩個後續郵政編碼形成一個範圍 - 第一個郵政編碼是範圍的最小值,第二個郵政編碼是最大值。

E.g.在

'1011AB', '1011AC',...,'1011AZ', '1011BA',...,'1011BD'

任何郵政編碼屬於區'A'

我的目標是通過郵政編碼和字典將廣告與地區進行匹配。


問題

我問前面的問題here和選擇遵循這一answer來解決這個問題。

因此,我使用下面的代碼的廣告匹配區,

def is_in_postcode_range(current_postcode, min, max): 
    return min <= current_postcode <= max 

def get_district_by_post_code(postcode): 
    for district, codes in postal_district.items(): 
     first_code = codes[0] 
     last_code = codes[-1] 
     if is_in_postcode_range(postcode, first_code, last_code): 
      if any(is_in_postcode_range(postcode, codes[i], codes[i+1]) for i in range(0, len(codes), 2)): 
       return district 
      else: 
       return None 

district = get_district_by_post_code(pc) 

對於一些郵政編碼這個工程。但是,許多郵政編碼不匹配。 1035CK,1072LL1059EC是無與倫比的,僅舉幾例。


什麼是錯?它是字典還是代碼?

我已經整理了字典。

回答

1

該構建:

if is_in_postcode_range(postcode, first_code, last_code): 
    if any(is_in_postcode_range(postcode, codes[i], codes[i+1]) 
      for i in range(0, len(codes), 2)): 
     return district 
    else: 
     return None 

假定該郵政區沒有重疊範圍。如果不是這樣,那麼你需要刪除:

else: 
    return None 
+0

我會被詛咒的。 – LucSpan