在 Python 中使用 re 查找多个匹配项(初学者问题)

我需要使用正则表达式和 Collection 找到多个匹配项(包含在列表中)。


我试过这段代码,但它显示空字典:


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)

感谢帮助!


MMMHUHU
浏览 253回答 1
1回答

千巷猫影

您需要另一种语法来重新也不要忘记在 += 之前初始化字典中的键import resome_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']+=1print(count_dictionary)UPD:根据评论,我们需要匹配项目的数量。像这样又快又脏的东西是怎么回事?import resome_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()]+=1print(count_dictionary)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python