簡體   English   中英

Python:正則表達式迭代以匹配列表元素中的單詞

[英]Python: regex iteration to match word in list element

設置

在倫敦抓取住房廣告,我在一個單元素列表中獲取每個廣告的地址,例如

address=['Brockham Drive, Brixton SW2']

我有一本將倫敦自治市與其所在地區聯系起來的字典,例如

boroughs={ 
'Barking_Dagenham':['Barking', ..., 'Rush Green'],
'Barnet':['Arkley', ..., 'Woodside Park'],
    ⋮
'Westminster':['Bayswater', ..., 'Westminster'],
}


問題

我想檢查區名是否在address 如果區在address ,那么我想創建變量districtborough指示區和相應的區。


代碼嘗試

(1)

 for bor in boroughs.keys(): # loop over boroughs for distr in boroughs[bor]: # loop over borough's districts if distr in address[0]: # assign if district in address district = distr borough = bor break else: district = 'unknown' borough = 'unknown'

(1) 不起作用。 也就是說,一切都被標記為'unknown'

我不確定我是否正確地進行了break ,也不確定if distr in address[0]:if distr in address[0]:是否是迭代時檢查匹配的正確方法。

(2)

 for bor in boroughs.keys(): # loop over boroughs for distr in boroughs[bor]: # loop over borough's districts district = re.search(r'\\b'distr'\\b', address[0]): borough = ? break else: district = 'unknown' borough = 'unknown'

對於 (2),我不確定在使用 '\\b' 時如何正確迭代 'bor'。 當迭代產生正確的地區匹配時,不確定如何分配相應的行政區。 另外,不確定我是否應該使用(2)而不是(1)。

我應該使用哪種方法,以及如何讓其中至少一種方法起作用?

您的代碼 try #1 是正確的,但缺少一個關鍵元素。 您只是跳出了內部 for 循環,但隨后您的代碼繼續循環通過外部 for 循環。 添加一個變量來檢查是否發現它跳出外部 for 循環。

found = False

for bor in boroughs.keys(): # loop over boroughs
  for distr in boroughs[bor]: # loop over borough's districts
    if distr in address[0]: # assign if district in address
      district = distr
      borough = bor
      found = True
      break
    else:
      district = 'unknown'
      borough = 'unknown'
  if found:
    break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM