问题描述
我使用大型数据库作为输入。我尝试了两种不同的方法,但都得到了相同的结果,每个循环都打印了第一行。
我不确定我在这里做错了什么。任何帮助将不胜感激。
我的代码
def cal_score(search_word):
for file in files:
with open(catcal_dir + file,"r") as infile:
content = json.load(infile)
if word in content["Convo"]:
convo_content = content["Convo"]
vectorizer = TfidfVectorizer(stop_words = {'english'},ngram_range=(1,3),lowercase=True)
tfidf_print = vectorizer.fit_transform([convo_content])
feature_names = vectorizer.get_feature_names()
feature_index = tfidf_print[0,:].nonzero()[1]
tfidf_scores = zip(feature_index,[tfidf_print[0,x] for x in feature_index])
data = {}
for word,score in [(feature_names[i],score) for (i,score) in tfidf_scores]:
if search_word == word:
data['score'] = score
data['Date'] = content['Date']
data['Term'] = word
df = pd.DataFrame(data,columns = ['Date','score','Term'],index=[0])
print(df)
print(cal_score('nekko'))
我得到的输出
Date score Term
0 May 16,1797 0.002463 nekko
Date score Term
0 march 04,1809 0.005918 nekko
Date score Term
0 July 09,1812 0.019306 nekko
Date score Term
0 march 04,1813 0.006175 nekko
Date score Term
0 July 23,1813 0.008521 nekko
我想要的输出
Date score Term
0 May 16,1797 0.002463 nekko
1 march 04,1809 0.005918 nekko
2 July 09,1812 0.019306 nekko
3 march 04,1813 0.006175 nekko
4 July 23,1813 0.008521 nekko
谢谢。
解决方法
您正在为数据库中的每个文件创建一个数据框,然后打印结果。您可能希望首先从每个文件中收集数据,然后在最后创建并打印一次数据框。