gpt4 book ai didi

python - 将字典值读取为正则表达式,返回匹配项

转载 作者:行者123 更新时间:2023-12-01 22:19:50 25 4
gpt4 key购买 nike

我有一个 python 字典,其中包含作为值的术语列表:

myDict = {
ID_1: ['(dog|cat[a-z+]|horse)', '(car[a-z]+|house|apple\w)', '(bird|tree|panda)'],
ID_2: ['(horse|building|computer)', '(panda\w|lion)'],
ID_3: ['(wagon|tiger|cat\w*)'],
ID_4: ['(dog)']
}

我希望能够将每个值中的列表项作为单独的正则表达式读取,如果它们匹配任何文本,则将匹配的文本作为单独字典中的键返回,并以其原始键(ID)作为值。

因此,如果这些术语被读取为用于搜索该字符串的正则表达式:

"dog panda cat cats pandas car carts"

我想到的一般方法是这样的:

for key, value in myDict:
for item in value:
if re.compile(item) = match-in-text:
newDict[match] = [list of keys]

预期输出为:

newDict = {
car: [ID_1],
carts: [ID_1],
dog: [ID_1, ID_4],
panda: [ID_1, ID_2],
pandas: [ID_1, ID_2],
cat: [ID_1, ID_3],
cats: [ID_1, ID_3]
}

仅当匹配的文本实际上与文本正文中的某些内容匹配时,才应将其作为 newDict 中的键返回。因此,在输出中,“Carts”列在那里,因为 ID_1 值中的正则表达式与其匹配。因此 ID 会列在输出字典中。

最佳答案

这是一个似乎符合您要求的简单脚本:

import re
from collections import defaultdict

text = """
the eye of the tiger
a dog in the manger
the cat in the hat
a kingdom for my horse
a bird in the hand
"""

myDict = {
'ID_1': ['(dog|cat|horse)', '(car|house|apples)', '(bird|tree|panda)'],
'ID_2': ['(horse|building|computer)', '(panda|lion)'],
'ID_3': ['(wagon|tiger|cat)'],
'ID_4': ['(dog)'],
}

newDict = defaultdict(list)

for key, values in myDict.items():
for pattern in values:
for match in re.finditer(pattern, text):
newDict[match.group(0)].append(key)

for item in newDict.items():
print(item)

输出:

('dog', ['ID_1', 'ID_4'])
('cat', ['ID_1', 'ID_3'])
('horse', ['ID_1', 'ID_2'])
('bird', ['ID_1'])
('tiger', ['ID_3'])

关于python - 将字典值读取为正则表达式,返回匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com