为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MMMHUHU 2023-06-20 13:33:39
我需要使用正则表达式和 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']+=1print(count_dictionary)感谢帮助!
查看完整描述

1 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

您需要另一种语法来重新


也不要忘记在 += 之前初始化字典中的键


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:根据评论,我们需要匹配项目的数量。像这样又快又脏的东西是怎么回事?


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)


查看完整回答
反对 回复 2023-06-20
  • 1 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信