如何在python中匹配多个单词

2024-07-04 08:41:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遍历列表“titles”中的字符串,我想打印“keywords\u to\u match”中单词匹配的字符串:

# import re
titles = ['walk to new zealand' , 'fly to mars' , 'drive to murica']
keywords_to_match = re.compile(r'(new zealand)?(mars)?(murica)')
for title in titles:
    # if any of words inside keywords_to_match are matched print title
    if keywords_to_match.search(title.lower()):
        print(title)
        # only prints "drive to murica"

这只打印“drive to murica”,但我希望它打印“titles”中的所有3个字符串


Tags: to字符串re列表newiftitlematch
3条回答

用“|”代替“?”来表达或表达关系

https://docs.python.org/3/library/re.html

将正则表达式更改为:

keywords_to_match = re.compile(r'\b(?:new zealand|mars|murica)\b')

我不确定你的案子需要正则表达式。您可以简单地执行以下操作:

titles = ['walk to new zealand', 'fly to mars', 'drive to murica']
[t for t in titles if any(k in t for k in keywords)]

这同样有效

keywords_to_match = re.compile(r'(new zealand|mars|murica)')

相关问题 更多 >

    热门问题