对于当前项目,我计划将下面的两个for循环结合起来,以便可以将输入保存在一个数据表中。
到目前为止,我尝试将循环(例如与for word, freq, element in ([common_words],[polarity_list]):
合并(导致了以下消息ValueError: not enough values to unpack (expected 3, got 1)
。
有什么聪明的调整来运行吗?对应的代码如下:
for i in ['Text_Pro','Text_Con','Text_Main']:
common_words = str(get_top_n_trigram(df[i], 150))
polarity_list = str([TextBlob(i).sentiment.polarity for i in common_words])
for element in polarity_list:
print(i, element)
for word, freq in common_words:
print(i, word, freq)
您可以使用:对于单词,枚举(common_words(中的频率:
由于common_words
似乎是元组列表,因此您可能需要将每个word
保存在polarity_list
:
for i in ['Text_Pro','Text_Con','Text_Main']:
common_words = get_top_n_trigram(df[i], 150)
polarity_list = [(word, TextBlob(word).sentiment.polarity) for word,_ in common_words]
for word, polarity in polarity_list:
print(i, word, polarity)
我认为您发布的代码有几个问题,这些问题共同混淆了:
common_words = str(get_top_n_trigram(df[i], 150))
这里的列表是一个tuples
列表:每个项目都是一个单词和一个数字。
然后这一行:
polarity_list = str([TextBlob(i).sentiment.polarity for i in common_words])
做错了两件事:迭代使用i
这将覆盖外部循环中的i
。另外,i
是一个tuple
,我想TextBlob
不喜欢。
为了解决这两个问题,我的代码通过首先丢弃tuple
的一个元素来生成polarity_list
,如下所示:word,_ in common_words
这样它就可以使用这样的word
:TextBlob(word)
.