python - 从python中的字典创建字典
问题描述
text="we are in pakistan and love pakistan and olx"
dict1={"pakistan": "COUNTRY", "olx": "ORG"}
我需要匹配文本中的键,如果它存在将该单词的索引存储为新字典中的键,其中值应该与该特定单词的 dict1 中的值相同,例如输出应该是这样的:
dict2={[10:17]:"COUNTRY",[27:34]:"COUNTRY","[40:42]:"ORG"}
解决方案
首先,我必须解决您的预期结果,即具有不可散列的列表,因为字典的键是不可能的。见https://wiki.python.org/moin/DictionaryKeys
产生类似的方法是使用re 库:
import re
text="we are in pakistan and love pakistan and olx"
dict1={"pakistan": "COUNTRY", "olx": "ORG"}
dict2 = {}
for key, value in dict1.items():
matched_all = re.finditer(key,text)
for matched in matched_all:
dict2[matched.span()] = value
print(dict2)
这会给你:
{(10, 18): 'COUNTRY', (28, 36): 'COUNTRY', (41, 44): 'ORG'}
推荐阅读
- php - “redirect_uri_mismatch”错误,自动附加“www” - Google OAuth2
- python - 如何在内置输出上调用 python 声音设备包
- ios - 从左边缘滑动以关闭 UIViewController
- c# - 如何进行身份验证以使用 Google Cloud Vision API
- r - 如何在没有 alpha 值的情况下将两个 geom_bar 相互叠加
- r - 如何在 dplyr 自定义函数中使用灵活的多参数过滤器
- python - 训练集和测试集上不同的标签编码器值不好?
- java - android lint 对缺少权限的误报
- java - Raspberry 无法从 Android 智能手机获取 UDP 数据
- python - 迭代两个数据帧以应用函数