Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用re查找多个匹配项(初学者问题)_Python_Re - Fatal编程技术网

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

在Python中使用re查找多个匹配项(初学者问题),python,re,Python,Re,我需要使用正则表达式和集合查找多个匹配项(包含在列表中) 我尝试了此代码,但它显示为空字典: 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

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

我尝试了此代码,但它显示为空字典:

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)

谢谢你的帮助

正如@han solo的评论所述,re需要另一种语法

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

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)

为什么您需要
regex
来实现这一点?只需使用
str.casefold
?像一些单词中的单词:…如果有的话(word.casefold()==w.casefold()表示单词中的w查找):…?这是家庭工作任务的要求不确定你想用
计数字典做什么
,但是,如果在没有看到示例输入想要得到什么输出的情况下试图理解,这是令人困惑的。对于不够清晰,我深表歉意:我需要计算word to查找与某些单词中的单词匹配的次数。例如:cat匹配了2次,所以结果应该是{'cat':2}完成了!干杯