如何修复Python正则表达式if语句匹配多水果短语的问题?
修复DataFrame中水果组合匹配的正则问题
我尝试在DataFrame中查找特定短语,需要匹配的水果组合包括:apples、bananas、oranges、apples and bananas、apples and oranges、bananas and oranges、apples, bananas, and oranges。但现有代码在仅匹配两个词的场景下失效,例如当行内容为'apple, banana, and orange'时,代码仅输出'apple and banana'。
原代码
for i in copy.loc[fruits]: print(i) #if match apple if re.match(r'((?=.*apple)|(?=.*apples))',i): #if says no apple if re.match(r'(\bno\b)',i) : print('no apples, only banana and oranges') print('') #if has apple and orange elif re.match(r'(?=.*orange)|(?=.*\boranges\b)',i): print('apples and oranges') print('') #if has apple and banana elif re.match(r'(?=.*banana)|(?=.*bananas)',i): print('apples and bananas') print('') #has apple, banana, and orange elif re.match(r'(?=.*banana)|(?=.*bananas)(?=.*orange)|(?=.*\boranges\b)',i): print('apples, bananas, and oranges') print('') #has only apple else: print('apples') print('') #only oranges elif re.match(r'(?=.*orange)|(?=.*\boranges\b)',i): print('oranges') print('') #only banana else: print('bananas') print('')
问题根源
- 正则逻辑顺序错误:多水果组合的判断放在双水果组合之后,永远不会触发(比如同时有香蕉和橙子的行,会先匹配到苹果+橙子或苹果+香蕉的条件)。
re.match误用:re.match仅从字符串开头匹配,无法匹配中间出现的水果关键词,应该用re.search。- 正则写法错误:多条件正向预查逻辑混乱,比如同时匹配香蕉和橙子应该用
且逻辑,而非或逻辑。 - 单复数处理繁琐:重复写
apple和apples,可以用正则简化。
修复后的代码
import re for i in copy.loc[fruits]: print(i) # 先标记各水果是否存在,统一处理单复数 has_apple = bool(re.search(r'\bapple(s)?\b', i, re.IGNORECASE)) has_banana = bool(re.search(r'\bbanana(s)?\b', i, re.IGNORECASE)) has_orange = bool(re.search(r'\borange(s)?\b', i, re.IGNORECASE)) # 单独处理"no apple"的情况 has_no_apple = bool(re.search(r'\bno\s+apple(s)?\b', i, re.IGNORECASE)) if has_no_apple: print('no apples, only banana and oranges') else: # 按组合数量从多到少判断,避免逻辑覆盖 if has_apple and has_banana and has_orange: print('apples, bananas, and oranges') elif has_apple and has_banana: print('apples and bananas') elif has_apple and has_orange: print('apples and oranges') elif has_banana and has_orange: print('bananas and oranges') elif has_apple: print('apples') elif has_orange: print('oranges') elif has_banana: print('bananas') print('')
修复说明
- 拆分逻辑:先单独判断每个水果是否存在,避免正则嵌套的混乱。
- 优先级顺序:先检查三水果组合,再双水果,最后单水果,彻底解决逻辑覆盖问题。
- 正则优化:用
(s)?匹配单复数,\b确保匹配完整单词,re.IGNORECASE提升容错性(可按需关闭)。 - 独立处理"no apple"场景:避免和正常存在苹果的逻辑冲突。
内容的提问来源于stack exchange,提问作者shorttriptomars
相关产品推荐
相关产品推荐

