【问题标题】:Python, regex - retrieve keywords from strings within dictionaryPython,正则表达式 - 从字典中的字符串中检索关键字
【发布时间】:2018-11-21 01:06:30
【问题描述】:

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

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

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

【问题讨论】:

  • 这段代码是 a) 不可运行 b) 无论如何可能是错误的。函数第一行的regexp 是什么?您确定要将keyword_regex 中的每个字符与| 字符连接起来吗?
  • 将该行更正为您可能的意思 - formatted_regexp = keyword_regexp.format(sep.join(list_of_keywords)) - 给出不同的错误,TypeError: unhashable type: 'list'
  • 粘贴在问题中的代码版本不是产生此错误的版本。

标签: python regex python-3.x dictionary findall


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2022-01-22
    • 2013-10-14
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 2016-01-13
    相关资源
    最近更新 更多