【发布时间】:2020-07-21 09:43:38
【问题描述】:
您好,我有一个字典列表,我想检查这些字典中是否包含单词列表中的特定单词,我想匹配确切的单词 例如,如果有一个名为 'badest' 的单词,我想匹配单词 'bad' 我不想包含它,这就是我使用正则表达式的原因 在这里,我已经做到了,但我只是想知道是否有更好、更易读的方法来做到这一点。
这是我的代码:
import re
words = ['bad', 'sad']
books = [
{
'title': 'bad book',
'description': 'this book contains bad text'
},
{
'title': 'book two',
'description': 'this book also contains Bad text'
},
{
'title': 'good book',
'description': 'this book will help you to overcome baddest habits'
},
{
'title': 'book four',
'description': 'this book is about a sad story'
}
]
def filter_books(book):
if not any(re.search(rf'\b{word}\b', book['title'], flags=re.IGNORECASE)
or re.search(rf'\b{word}\b', book['description'], flags=re.IGNORECASE)
for word in words):
return True
return False
good_books = list(filter(filter_books, books))
print(good_books)
【问题讨论】:
标签: python python-3.x regex list filter