Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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,regex-从字典中的字符串检索关键字_Python_Regex_Python 3.x_Dictionary_Findall - Fatal编程技术网

Python,regex-从字典中的字符串检索关键字

Python,regex-从字典中的字符串检索关键字,python,regex,python-3.x,dictionary,findall,Python,Regex,Python 3.x,Dictionary,Findall,我有一本字典,长字符串作为键,集合作为值。我还有一个关键字列表。比如说, 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'] 我想用关键字列表中的数字或单词将新值过滤到元组中。因此,上述词典将被转换为 fin

我有一本字典,长字符串作为键,集合作为值。我还有一个关键字列表。比如说,

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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第5行,过滤器中的两个关键字的默认值
文件“”,第5行,在
findall中的文件“/anaconda/lib/python3.6/re.py”,第222行
返回编译(模式、标志).findall(字符串)
TypeError:应为字符串或类似字节的对象

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

您可以拆分每个字符串,并在关键字列表中检查数字或单词的存在:

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'}}

此代码a)不可运行,b)无论如何可能是错误的。函数的第一行中的
regexp
是什么?您确定要将
关键字_regex
中的每个字符与
字符连接起来吗?将该行更正为您想当然的意思-
格式化_regexp=keyword _regexp.format(sep.join(关键字列表))
-会产生不同的错误,
TypeError:unhabable类型:“list”
。问题中粘贴的代码版本不是导致此错误的版本。