2017-05-16 216 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