下面的正則運算式目前作業正常。它將回傳 IF f1 并且 f2 或 f3 匹配。
我需要幫助弄清楚如何僅在 f1 匹配時列印 else 例如 print("哪個城市和哪個月份?)
import re
string = ['I am looking to rent a home in Los Angeles']
for s in string:
f1 = re.findall(r'(.{0,50}\b(home|house|condo)\b.{0,50})',s, re.IGNORECASE)
if f1:
f2 = re.findall(r'(.{0,50}\b(los angeles|la)\b.{0,50})',f1[0][0], re.IGNORECASE)
if f2:
print("For what month?")
f3 = re.findall(r'(.{0,50}\b(june|july|august)\b.{0,50})',f1[0][0], re.IGNORECASE)
if f3:
print("For what city?")```
uj5u.com熱心網友回復:
確定f1匹配后,收集f2并f3匹配。然后檢查是否f2或f3匹配,否則,做f1阻塞:
import re
string = ['I am looking to rent a home in Los Angeles']
for s in string:
f1 = re.search(r'.{0,50}\b(home|house|condo)\b.{0,50}',s, re.IGNORECASE)
if f1:
f2 = re.findall(r'(.{0,50}\b(los angeles|la)\b.{0,50})', f1.group(), re.IGNORECASE)
f3 = re.findall(r'(.{0,50}\b(june|july|august)\b.{0,50})', f1.group(), re.IGNORECASE)
if f2:
print("For what month?")
elif f3:
print("For what city?")
else:
print("Only f1 fired, not f2 and f3")
else:
print("No f1!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460396.html
