Python TypeError:必须是str,而不是list
问题是输出结果未保存在csv文件中。 我正在使用此代码对单词“正”和“负”进行加权。我想保存在csv文件中。首先,读取csv文件,应用tf idf并在shell上显示输出,但在csv文件中写入结果时会显示错误Python TypeError:必须是str,而不是list,python,csv,tf-idf,Python,Csv,Tf Idf,问题是输出结果未保存在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
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
文档1中的关键词
回溯(最近一次呼叫最后一次):
文件“C:\Python34\webcrawler Final.py”,第38行,在
最终=打开(“tfidf.csv”,“w”)。写入(已排序的单词)
TypeError:必须是str,而不是list
尝试执行此操作
sorted_words = ''.join(sorted(scores.items(), reverse=True))
由于您没有在帖子中指定,我不知道元组值之间的分隔符是什么,因此我添加了一个
'\n'
。您可以将其更改为'
或任何您想要的内容
final=open(“tfidf.csv”、“w”).write('\n.join(“%s,%s”%x表示x表示已排序的单词))
尝试final=open(“tfidf.csv”、“w”).write(str(已排序的单词))
使用open(“tfidf.csv”、“w”).write(“.join(已排序的单词))
,这将连接列表项并返回字符串,”。join(['1','2','3']))
将返回1 2 3
,但如果您想以列表的格式编写,请尝试@Borja方法。@Borja它可以工作,谢谢,但我不想用数据保存。e、 g the('Pakistan',0.0),我希望以这种方式保存数据,即巴基斯坦,0.0您尝试过@ZdaR解决方案吗?哦@Anaya,Pakistan
interest;),您可以尝试“,”。join('India',10.0))
返回India,10.0
,并将其嵌入到您的代码中:打开(“tfidf.csv”,“w”)。写入(,”。join(排序词))
在文件中保存数据时出现问题。共有三个文档,只有最后一个文档保存在file.file=open(“example1.txt”,“r”)。read()file2=open(“heading.txt”,“r”)。read()file3=open(“example2.txt”,“r”)。read()document=tb(file)document2=tb(file2)document3=tb(file3)bloblist=[document,document2,document3]在这些代码行之后,上面提到了剩余的代码。