赋值前引用的 WordCloud '局部变量 'n'

WordCloud 'local variable 'n' referenced before assignment

我是 python 的新手,我正在尝试定义一个函数,该函数将 return 来自特定 city_state 的工作标记的 WordCloud。代码独立运行,但作为一个函数,我不知道如何修复错误。我得到一个

UnboundLocalError: local variable 'comment_words' referenced before assignment

def jobs_wordcloud(city_state):
cols = ['base_tokens']
for val in jobs_df.loc[jobs_df['city_state'] == city_state, cols]:
    val = str(val)
    tokens = word_tokenize(val)
    tokens = re.sub('[^a-zA-Z 0-9]', '', val)
    tokens = tokens.lower().split()
    lemmatizer = WordNetLemmatizer()
    tokens = [w for w in tokens if not w in stop_words]
    tokens = [lemmatizer.lemmatize(w.lower().strip()) for w in tokens]
    comment_words += " ".join(tokens) + " "

wordcloud = WordCloud(width = 800, height = 800,
    background_color = 'white',
    stopwords = stop_words,
    min_font_size = 10).generate(comment_words)
  
plt.figure(figsize = (10, 10), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()

return plt.show()

这是我遇到的错误:

UnboundLocalError                         Traceback (most recent call last)
<ipython-input-31-8df36e8cfe41> in <module>()
----> 1 jobs_wordcloud('San Francisco, CA')

<ipython-input-30-1a42912ec34f> in jobs_wordcloud(city_state)
     11         tokens = [w for w in tokens if not w in stop_words]
     12         tokens = [lemmatizer.lemmatize(w.lower().strip()) for w in tokens]
---> 13         comment_words += " ".join(tokens) + " "
     14 
     15     wordcloud = WordCloud(width = 800, height = 800,

UnboundLocalError: local variable 'comment_words' referenced before assignment

jobs_wordcloud 函数中开始循环之前定义 comment_words = ''

由于您正在有效地执行 comment_words = comment_words + SOMETHING,python 需要知道 comment_words 的值是多少。