Python 如何使用字典将类别与句子匹配
我有以下句子和格言:Python 如何使用字典将类别与句子匹配,python,list,dictionary,text,categorization,Python,List,Dictionary,Text,Categorization,我有以下句子和格言: dictio = {'col1': ['smell', 'scent'], 'col2': ['color', 'red','blue'],'col3':['long','small']} Sentence = ["The color of pants is blue and red","The tshirt smell very good", "She is a tall person", "The monkey is playing"] 我想将一个句子与其类别匹配
dictio = {'col1': ['smell', 'scent'], 'col2': ['color', 'red','blue'],'col3':['long','small']}
Sentence = ["The color of pants is blue and red","The tshirt smell very good", "She is a tall person",
"The monkey is playing"]
我想将一个句子与其类别匹配:
dic_keys = dictio.keys()
resultat = []
for key_dics in dic_keys:
for values in dictio[key_dics]:
for sent in Sentence:
if values in sent.lower().split():
resultat.append(key_dics)
我得到以下结果:
['col1','col2','col2','col3']
但我需要这样的结果:
['col2','col1','col3','KO']
当我用else条件完成for循环时,我得到了一个奇怪的结果
我需要您的帮助来解决此问题。您的问题和代码中有很多问题 你的例外结果是错误的-当它需要5个值时,它只有4个值-而且,col3应该有
气味
,而不是小的
,以获得你需要的结果
可以优化for循环
dictio = {'col1': ['smell', 'scent'], 'col2': ['color', 'red','blue'],'col3':['long','smell']}
Sentence = ["The color of pants is blue and red","The tshirt smell very good", "She is a tall person", "The monkey is playing"]
res = []
flag = True
for sent in Sentence:
for k, v in dictio.items():
if [x for x in v if x in sent.split()]:
res.append(k)
flag = False
if flag:
res.append("KO")
flag = True
print(res)
# ['col2', 'col1', 'col3', 'KO', 'KO']
您的问题和代码中有很多问题 你的例外结果是错误的-当它需要5个值时,它只有4个值-而且,col3应该有
气味
,而不是小的
,以获得你需要的结果
可以优化for循环
dictio = {'col1': ['smell', 'scent'], 'col2': ['color', 'red','blue'],'col3':['long','smell']}
Sentence = ["The color of pants is blue and red","The tshirt smell very good", "She is a tall person", "The monkey is playing"]
res = []
flag = True
for sent in Sentence:
for k, v in dictio.items():
if [x for x in v if x in sent.split()]:
res.append(k)
flag = False
if flag:
res.append("KO")
flag = True
print(res)
# ['col2', 'col1', 'col3', 'KO', 'KO']