如何创建一个字典,其中键是词干,值是带有该词干的单词列表?



在python中,我已经有一个单词列表和一个词干列表。如何创建一个字典,其中键是词干,值是具有该词干的单词列表,如下所示:

{‘achiev’: [‘achieved’, ‘achieve’] ‘accident’: [‘accidentally’, ‘accidental’] … }

stems = ['accident', 'achiev']
words = ['achieved', 'accidentally', 'achieve', 'accidental']
results = {}
for stem in stems:
stem_words = [w for w in words if w.startswith(stem)]
results[stem] = stem_words
print(results)

指纹:

{'accident': ['accidentally', 'accidental'], 'achiev': ['achieved', 'achieve']}

您可以使用字典理解列表理解使用一行代码来执行此操作:

{stem: [w for w in words if w.startswith(stem)] for stem in stems}

最新更新