【发布时间】:2020-07-14 23:24:24
【问题描述】:
对于当前项目,我想遍历 Pandas DataFrame 中定义为 common_words 的单词对列表。
当调用for word in common_words: 行时,我收到错误TypeError: 'NoneType' object is not iterable。我已经检查了可能的方法来解决这个问题,但还没有找到任何解决方案。
有什么聪明的调整可以让它运行吗?
对应的代码部分如下所示:
# Open the file to write to
with open('sp500-1.csv', 'w', newline='') as file:
writer = csv.writer(file)
# Write headers
writer.writerow(["Section", "TFI"])
# Loop over the JSON objects
for i in ['txt_pro','txt_con','txt_adviceMgmt','txt_main']:
# Loop over the common words inside the JSON object
common_words = get_top_n_bigram_Group2(df[i], 500)
for word in common_words:
# Print and write row.
print(df2)
writer.writerow([df2])
而get_top_n_bigram_Group2的定义如下:
def get_top_n_bigram_Group2(corpus, n=None):
# settings that you use for count vectorizer will go here
tfidf_vectorizer=TfidfVectorizer(ngram_range=(2, 2), stop_words='english', use_idf=True).fit(corpus)
# just send in all your docs here
tfidf_vectorizer_vectors=tfidf_vectorizer.fit_transform(corpus)
# get the first vector out (for the first document)
first_vector_tfidfvectorizer=tfidf_vectorizer_vectors[0]
# place tf-idf values in a pandas data frame
df1 = pd.DataFrame(first_vector_tfidfvectorizer.T.todense(), index=tfidf_vectorizer.get_feature_names(), columns=["tfidf"])
df2 = df1.sort_values(by=["tfidf"],ascending=False)
print(df2)
【问题讨论】:
-
根据错误,看起来
common_words是None。你检查过你的函数的输出来验证返回吗? -
感谢您的意见,我明白您的意思。终端中的打印输出正在工作。有没有办法将 common_words 分配给正确的数据? (您很可能需要更多代码)
-
我已附加
get_top_n_bigram_Group2的代码。如果在这种情况下可以找到为什么common_words是None的解决方案,那就太好了。非常感谢。 -
你没有在你的函数中
return。如果没有 return 语句,函数会隐式返回None -
这能回答你的问题吗? return, return None, and no return at all?