Python、正则表达式 - 从字典中的字符串中检索关键字

Python, regex - retrieve keywords from strings within dictionary

我有一个字典,其中长字符串作为键,集合作为值。我还有一个关键字列表。例如,

dict1 = {"This is the long key with 9 in it.": {'value1'}, 'I have another long string with 4 and keyword': {'value2'}} 
list_of_keywords = ['this', 'is', 'a', 'keyword']

我想将新值过滤到包含关键字列表中的数字或单词的元组中。所以上面的字典会变成

final_dict1 = {('9', 'this', 'is'): {'value1'}, ('4', 'keyword'): {'value2'}}

我下面有两个正则表达式可以工作,我有一个函数可以完成我希望它做的大部分事情:

import re
digit_regxep = r"\s\b\d{1,3}\b"
keyword_regexp = r"\b({})\b"

def filter_dict_values_for_keyword_digit(dict1, keyword_regexp, digit_regexp, list_of_keywords, sep='|'):
    formatted_regexp = regexp.format(sep.join(keyword_regexp))
    word = re.compile(formatted_regexp)
    word1 = re.compile(digit_regexp)
    filtered_dict = dict1.update(((list(re.findall(word1, k)), list(re.findall(word, k))), v) for k, v in dict1.items())
    return filtered_dict

但每当我尝试 运行 时,我都会收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in filter_dict_values_for_two_keywords
  File "<stdin>", line 5, in <genexpr>
  File "/anaconda/lib/python3.6/re.py", line 222, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

我对字典的组成有什么误解影响了我的功能吗?我无法确定它是否是函数中的问题,或者是否是因为我的初始值是一个集合而不是一个字符串。

而不是 re,您可以拆分每个字符串并检查 list_of_keywords 中的数字或单词是否存在:

import re
dict1 = {"This is the long key with 9 in it.": {'value1'}, 'I have another long string with 4 and keyword': {'value2'}} 
list_of_keywords = ['this', 'is', 'a', 'keyword']
new_results = {tuple(i for i in a.split() if i.isdigit() or i.lower() in list_of_keywords):b for a, b in dict1.items()}

输出:

{('This', 'is', '9'): {'value1'}, ('4', 'keyword'): {'value2'}}