从 python 中的字典创建字典
Creating a dictionary from a dictionary in 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 library:
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'}
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 library:
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'}