【问题标题】:How to filter a list of dictionaries by checking if another list of words are existed in those dictionaries?如何通过检查字典中是否存在另一个单词列表来过滤字典列表?
【发布时间】: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


    【解决方案1】:
    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 is_word_present(word):
        for w in words:
            if (re.search(rf'\b{w}\b', word, flags=re.IGNORECASE)):
                return True
        return False
    
    
    def _filter(books):
        res = []
        for book in books:
            if is_word_present(book['title']) or is_word_present(book['description']):
                pass
            else:
                res.append(book)
        return res
    
    
    good_books = _filter(books)
    print(good_books)
    

    【讨论】:

      【解决方案2】:

      你可以使用类似的东西:

      def filter(book):
          result = False
          all = book['title'] + ' ' + book['description']
          for item in words:
              if item in re.split(pattern='.| |,|;', string=all):
                  result = True
          return result
      

      这会检查您的words 列表中的单词之一是否在标题或描述中。一件坏事:这是区分大小写的。

      【讨论】:

        【解决方案3】:

        这里有几种方法,

        # using set data-structure
        
        words = {'bad', 'sad'}
        
        # 6.99 µs ± 426 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
        print([
            book for book in books
            if set(book['title'].lower().split()).intersection(words)
               or set(book['description'].lower().split()).intersection(words)
        ])
        

        # using regex
        
        import re
        
        words = re.compile("|".join(words), re.IGNORECASE)
        
        # 11 µs ± 874 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
        print([
            book for book in books
            if words.findall(book['title'])
               or words.findall(book['description'])
        ])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-30
          • 1970-01-01
          • 2022-01-19
          • 1970-01-01
          • 1970-01-01
          • 2017-09-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多