在 Python 中使用 re 查找多个匹配项(初学者问题)
Find multiple matches using re in Python (beginner question)
我需要使用正则表达式和集合查找多个匹配项(包含在列表中)。
我试过这段代码,但它显示空字典:
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)
更新:
根据评论,我们需要匹配项目的数量。像这样又快又脏的东西是怎么回事?
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)
我需要使用正则表达式和集合查找多个匹配项(包含在列表中)。
我试过这段代码,但它显示空字典:
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)
更新: 根据评论,我们需要匹配项目的数量。像这样又快又脏的东西是怎么回事?
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)