设置
使用 Scrapy ,我正在抓取房屋广告。每个房屋广告,我都会获得一个邮政编码。
我有一本将邮政编码与地区联系起来的字典,
postal_district = {'A': ['1011AB', '1011BD', '1011BG', '1011CE',
'1011CH', '1011CZ', '1011DB', '1011DD']}
可以查看整本词典here .
列表中每两个后续邮政编码构成一个范围——第一个邮政编码是范围的最小值,第二个邮政编码是最大值。
例如
中的任何邮政编码'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、1072LL、1059EC 是无与伦比的,仅举几例。
怎么了?是字典还是代码?
我已经整理好了词典。
请您参考如下方法:
这个结构:
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
