簡體   English   中英

構造正則表達式模式以識別單詞的子集

[英]Construct regex pattern to identify a sub set of words

我想使用正則表達式模式使用以下字典的values()來識別單詞的子集。

creategarbageterms = {'tim_tam' : ['tim_tam','yummy_tim_tam', 'berry_tim_tam'],
                      'pudding': ['pudding', 'chocolate_pudding', 'biscuits', 'tiramusu'],
                      'ice_cream': ['ice_cream', 'vanilla_ice_cream']}

即,給出以下字符串;

**Term  ->    Output**
wow_yummy_tim_tam -> yes
melted_tim_tam ->yes
berry_tim_tam -> Yes
cherry_berry_tim_tam -> yes
wow_tam -> No
wow_m -> No
wow_ti -> No
Wow_tim_t -> No

我當前的代碼/模式如下。

creategarbageterms = {'tim_tam' : ['tim_tam','yummy_tim_tam', 'berry_tim_tam'],
                      'pudding': ['pudding', 'chocolate_pudding', 'biscuits', 'tiramusu'],
                      'ice_cream': ['ice_cream', 'vanilla_ice_cream']}

pattern = re.compile(r'|'.join([r'(\s|\b){}\b'.format(x) for x in creategarbageterms.values()]))
if re.findall(pattern, "wow_m".replace("_", " ")):
    print("yes")
else:
   print("no")

但是,在我當前的代碼中,上述“ No條款也被接受。 請讓我知道我在哪里做錯了?

我認為您不需要正則表達式來檢查字符串中是否存在。 而是使用inre拆分字符串:

import re
creategarbageterms = {'tim_tam' : ['tim_tam','yummy_tim_tam', 'berry_tim_tam'],
                  'pudding': ['pudding', 'chocolate_pudding', 'biscuits', 'tiramusu'],
                  'ice_cream': ['ice_cream', 'vanilla_ice_cream']}

s =  ['wow_yummy_tim_tam', 'melted_tim_tam, berry_tim_tam', 'cherry_berry_tim_tam', 'wow_tam', 'wow_m', 'wow_ti', 'Wow_tim_t']
for c in s:
   truthy = any(any(i in c for i in b) for a, b in creategarbageterms.items())
   if truthy:
       print("Yes")
   else:
       print("no")

輸出:

Yes
Yes
Yes
no
no
no
no

暫無
暫無

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

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