繁体   English   中英

Python使用“触发字符串”列表的字典从列表列表中输出新的带标签的字典

[英]Python using dict of “triggers strings” lists to output a new labeled dict from a list of lists

我已经预定义了字符串触发器列表的字典:

triggers = {'academic': ['studied at', 'studies at', 'studies', 'studies at'],
     'age': ['years old','months old'],
     'gender': ['male', 'female'],
     'pets': ['dog','cat'],
     'location': ['Lived in','Lives in']}

我有一个以前未知的分组信息数据列表的列表,例如:

example_list_of_list = [['Former Teacher of math at'],
 ['Studies programming at', 'Stackoverflow'],
 ['Lives in','Chicago'],
 ['owns','dog', 'cat']

我想使用匹配的预定义键值将每个匹配列表元素附加到新字典中,例如:

{'academic': ['Former Teacher of math at'],
'age': None, # np.nan or []
'gender': None, # np.nan or []
'pets': ['owns','dog','cat']
'location': ['Lives in','Chicago']
 }

谢谢!

我认为,使用集合语义可以最轻松地做到这一点:

result = {}
for input in example_list_of_list:
    for key, triggerset in triggers.items():
        if not input.isdisjoint(triggerset):
            result[key] = result.get(key,[]).append(input)

尽管注意以下几点:

  • triggers应该是一个dictset不是list秒。
  • example_list_of_lists应该是setlist
  • resultlistlistdict ,因为可能有多个输入匹配

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM