删除python中的短同义词

2024-05-19 23:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

synonyms_dict = {'look': ['gaze', 'see', 'glance', 'watch', 'peruse'],
'put': ['place', 'set', 'attach', 'keep', 'save', 'set aside', 
'effect', 
'achieve', 'do', 'build'],
'beautiful': ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 
'magnificent'],
'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 
'slack'], 
'dangerous': ['perilous', 'hazardous', 'uncertain']}
remove_short_synonyms(synonyms_dict)
print("1.")
print_dict_in_key_order(synonyms_dict)    
synonyms_dict = {'come': ['approach', 'advance', 'near', 'arrive', 'reach'],
'show': ['display', 'exhibit', 'present', 'point to', 'indicate', 'explain', 
'prove', 'demonstrate', 'expose'],
'good': ['excellent', 'fine', 'superior', 'wonderful', 'grand', 'superb', 
'edifying'],
'bad': ['evil', 'immoral', 'wicked', 'contaminated', 'spoiled', 'defective',  
'substandard', 'faulty', 'improper', 'inappropriate']}
remove_short_synonyms(synonyms_dict)
print("2.")
print_dict_in_key_order(synonyms_dict)

我试图从每个对应的同义词列表中删除少于7个字符的所有同义词,并且函数对每个对应的同义词列表进行排序。我试过这个功能。在

^{pr2}$

期望:

 beautiful : ['dazzling', 'handsome', 'magnificent', 'splendid']
 dangerous : ['hazardous', 'perilous', 'uncertain']
 look : []
 put : ['achieve', 'set aside']
 slow : ['gradual', 'leisurely', 'tedious', 'unhurried']
 2.
 bad : ['contaminated', 'defective', 'immoral', 'improper', 'inappropriate', 
 'spoiled', 'substandard']
 come : ['advance', 'approach']
 good : ['edifying', 'excellent', 'superior', 'wonderful']
 show : ['demonstrate', 'display', 'exhibit', 'explain', 'indicate', 'point 
 to', 'present']

Tags: putdictsynonymsprintslowset同义词look
1条回答
网友
1楼 · 发布于 2024-05-19 23:26:27

不要从原始版本中删除,只需使用dictionary comprehension重建一个过滤后的版本,并在值上使用max-size过滤器,然后馈送到sorted对值列表进行排序:

synonyms_dict = {'look': ['gaze', 'see', 'glance', 'watch', 'peruse'],
'put': ['place', 'set', 'attach', 'keep', 'save', 'set aside',
'effect',
'achieve', 'do', 'build'],
'beautiful': ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid',
'magnificent'],
'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious',
'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def remove_short_synonyms(s):
    return {k:sorted([i for i in v if len(i)>7]) for k,v in s.items()}


print(remove_short_synonyms(synonyms_dict))

结果:

^{pr2}$

相关问题 更多 >