简体   繁体   中英

Find multiple matches using re in Python (beginner question)

I need to find multiple matches (contained in a list) using regular expression and Collection.

I tried this code, but it shows empt dictionary:

some_words_lst = ['caT.', 'Cat', 'Dog', 'paper', 'caty', 'London', 'loNdon','londonS']

words_to_find = ['cat', 'london']

r = re.compile('(?:.*{})'.format(i for i in words_to_find),re.IGNORECASE)

count_dictionary = {}

for item in some_words_lst:
    if r.match(item):
        count_dictionary['i']+=1

print(count_dictionary)

Thanks for help!

as stated in comment by @han solo you need another syntax for re

also do not forget to initialize key in dictionary before you +=

import re
some_words_lst = ['caT.', 'Cat', 'Dog', 'paper', 'caty', 'London', 'loNdon','londonS']

words_to_find = ['cat', 'london']

r = re.compile('|'.join(words_to_find), re.IGNORECASE)

count_dictionary = {"i": 0}

for item in some_words_lst:
    if r.match(item):
        count_dictionary['i']+=1

print(count_dictionary)

UPD: according to the comment we need count of matched items. What is about something quick and dirty like this?

import re
some_words_lst = ['caT.', 'Cat', 'Dog', 'paper', 'caty', 'London', 'loNdon','londonS']

words_to_find = ['cat', 'london']

r = re.compile('|'.join(words_to_find), re.IGNORECASE)

count_dictionary = {word: 0 for word in words_to_find}

for item in some_words_lst:
    if r.match(item):
        my_match = r.match(item)[0]
        count_dictionary[my_match.lower()]+=1

print(count_dictionary)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM