【问题标题】:How to creat a dictionary where the key is the stem and the value is a list of words with that stem?如何创建一个字典,其中键是词干,值是具有该词干的单词列表?
【发布时间】:2019-09-12 14:52:51
【问题描述】:

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

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

【问题讨论】:

  • 你尝试过什么,它到底有什么问题?
  • 您的输入会是什么样子?有一个类似的数据结构,称为Trie,经常使用。您将如何使用您的结构?

标签: python nlp


【解决方案1】:
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']}

【讨论】:

    【解决方案2】:

    您可以使用 dict comprehnsionlist comprehnsion 用一行代码完成此操作:

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

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      相关资源
      最近更新 更多