首页 > 解决方案 > 函数后返回的语法

问题描述

我尝试从 gensim 重现这行代码

import gensim
def coherence_values_computation(dictionary, corpus, texts, limit, start=2, step=3):
   coherence_values = []
   model_list = []
   for num_topics in range(start, limit, step):
      model = gensim.models.wrappers.LdaMallet(
         mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word
      )
      model_list.append(model)
   coherencemodel = CoherenceModel(
      model=model, texts=texts, dictionary=dictionary, coherence='c_v'
   )
   coherence_values.append(coherencemodel.get_coherence())
return model_list, coherence_values

但是在返回函数中,我收到此错误:

File "<ipython-input-10-65490721eef3>", line 13
    return model_list, coherence_values)
    ^
SyntaxError: invalid syntax

发生这种情况有什么想法吗?

标签: pythonpython-3.xgensim

解决方案


return应该在函数内部。缩进应该是:

def coherence_values_computation(dictionary, corpus, texts, limit, start=2, step=3):
   coherence_values = []
   model_list = []
   for num_topics in range(start, limit, step):
      model = gensim.models.wrappers.LdaMallet(
         mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word
      )
      model_list.append(model)
   coherencemodel = CoherenceModel(
      model=model, texts=texts, dictionary=dictionary, coherence='c_v'
   )
   coherence_values.append(coherencemodel.get_coherence())
   return model_list, coherence_values

推荐阅读