【发布时间】:2018-04-08 04:59:25
【问题描述】:
已提供解决方案 - 谢谢@ekhumoro! 我有一个 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 中的键返回仅当它们实际上匹配了文本正文中的某些内容。因此,在输出中,“购物车”列在那里,因为 ID_1 值中的正则表达式与之匹配。因此 ID 列在输出字典中。 解决方案
import re
from collections import defaultdict
text = """
the eye of the tiger
a doggies in the manger
the cat in the hat
a kingdom for my horse
a bird in the hand
the cationic cataclysm
the pandamonious panda pandas
"""
myDict = {
'ID_1': ['(dog\w+|cat\w+|horse)', '(car|house|apples)',
'(bird|tree|panda\w+)'],
'ID_2': ['(horse|building|computer)', '(panda\w+|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)
【问题讨论】:
-
你能提供一个预期输出的例子吗?
-
@scharette newDict 是我希望实现的输出。
-
为了提供更多上下文 - myDict 的值包含一个正则表达式列表。它们正在针对一组文本运行,最后,只应返回这些 RegEx 的匹配项。很抱歉造成混乱并且没有在问题中提供更多信息,但感谢所有已经提供答案的人。但不幸的是,这不是通过简单的字符串格式可以完成的。需要通过将这些术语作为正则表达式运行来完成。
-
为什么
newDict输出中没有汽车或苹果? -
@AndyHayden 我在问题中提供了更多信息。
标签: python regex python-3.x dictionary