Skip to main content
 首页 » 编程设计

python之检查列表中的字符串是否取决于最后两个字符

2024年10月01日25exmyth

设置

我正在使用 Scrapy 来抓取房屋广告。每个广告我检索一个邮政编码,它由四个数字后跟两个字母组成,例如1053ZM。

我有一个 excel 表,按以下方式将地区链接到邮政编码,

district    postcode_min    postcode_max 
   A           1011AB           1011BD 
   A           1011BG           1011CE 
   A           1011CH           1011CZ 

因此,第二行表明从 1011AB, 1011AC,..., 1011AZ, 1011BA,...,1011BD 的邮政编码属于 A 区。

实际列表包含 1214 行。


问题

我想使用其邮政编码和列表将每个广告与其各自的地区相匹配。

我不确定执行此操作的最佳方法是什么,以及如何执行此操作。

我想出了两种不同的方法:

  1. 创建介于 postcode_min 和 postcode_max 之间的所有邮政编码,将所有邮政编码及其各自的区分配给字典,以便随后使用循环进行匹配。

即创建,

 d = {'A': ['1011AB','1011AC',...,'1011BD', 
            '1011BG','1011BH',...,'1011CE', 
            '1011CH','1011CI',...,'1011CZ'], 
      'B': [...],            
      } 

然后,

found = False 
for distr in d.keys(): # loop over districts 
     for code in d[distr]: # loop over district's postal codes 
         if postal_code in code: # assign if ad's postal code in code                  
             district = distr 
             found = True 
             break 
         else: 
             district = 'unknown' 
     if found: 
         break 
  1. 让Python理解postcode_min和postcode_max之间有一个范围,将范围和它们各自的分区分配给字典,并使用循环匹配。

即类似的东西,

d = {'A': [range(1011AB,1011BD), range(1011BG,1011CE),range(1011CH,1011CZ)], 
     'B': [...] 
    } 

然后,

found = False 
for distr in d.keys(): # loop over districts 
     for range in d[distr]: # loop over district's ranges 
         if postal_code in range: # assign if ad's postal code in range                  
             district = distr 
             found = True 
             break 
         else: 
             district = 'unknown' 
     if found: 
         break 

问题

对于方法 1:

  • 如何创建所有邮政编码并将它们分配给字典?

对于方法 2:

我使用 range() 进行解释,但我知道 range() 不能像这样工作。

  • 如上例所示,我需要什么才能有效地拥有 range()?
  • 如何正确地遍历这些范围?

我认为我更喜欢方法 2,但我很乐意使用其中任何一种。或者,如果您有其他解决方案,也可以使用其他解决方案。

请您参考如下方法:

您可以像这样在 excel 中收集值

d = {'A': ['1011AB', '1011BD', '1011BG', '1011CE',  '1011CH', '1011CZ'], 
     'B': ['1061WB', '1061WB'], 
     } 
 
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 d.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 

用法:

print get_district_by_post_code('1011AC'): A 
print get_district_by_post_code('1011BE'): None 
print get_district_by_post_code('1061WB'): B