如何使用字典将类别与句子匹配
How to match a category with sentence using dictionary
我有以下句子和字典:
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 condition.I 完成我的 for 循环时,结果很奇怪。
我需要你的帮助来解决这个问题。
你的问题和代码都有很多问题。
您的例外结果是错误的 - 当它需要 5 个时它只有 4 个值 - 而且,col3 应该有 smell
而不是 small
才能得到你需要的结果。
您的 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']
我有以下句子和字典:
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 condition.I 完成我的 for 循环时,结果很奇怪。
我需要你的帮助来解决这个问题。
你的问题和代码都有很多问题。
您的例外结果是错误的 - 当它需要 5 个时它只有 4 个值 - 而且,col3 应该有 smell
而不是 small
才能得到你需要的结果。
您的 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']