【发布时间】:2015-06-03 06:50:08
【问题描述】:
问题是输出结果没有保存在 csv 文件中。 我正在使用此代码对正面和负面的词进行加权。我想保存在 csv 文件中。首先,读取 csv 文件,应用 tf-idf 并在 shell 上输出显示,但是当结果写入 csv 时显示错误文件。
for i, blob in enumerate(bloblist):
print("Top words in document {}".format(i + 1))
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
sorted_words = sorted(scores.items(), reverse=True)
print(sorted_words)
final = open("tfidf.csv", "w").write(sorted_words)
print(final)
print("done")
错误是:
Top words in document 1
Traceback (most recent call last):
File "C:\Python34\webcrawler-Final.py", line 38, in <module>
final = open("tfidf.csv", "w").write(sorted_words)
TypeError: must be str, not list
【问题讨论】:
-
试试
final = open("tfidf.csv", "w").write(str(sorted_words)) -
使用
open("tfidf.csv", "w").write(" ".join(sorted_words)),这将连接您的列表项并返回一个字符串," ".join(['1', '2', '3'])将返回1 2 3,但如果您想以列表的格式写入,请尝试@Borja 方法。 -
@Borja 它可以工作,谢谢,但我不想用数据保存括号。例如('Pakistan', 0.0),我希望以这种方式保存数据,即巴基斯坦,0.0
-
您尝试过@ZdaR 解决方案吗?
-
哦 @Anaya ,
Pakistan有趣 ;) ,您可以尝试返回", ".join(('India', 10.0))并将其嵌入到您的代码中:open("tfidf.csv", "w").write(", ".join(sorted_words))