类型错误:必须是str,而不是lis

2024-09-24 02:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是输出结果没有保存在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

Tags: 文件csvinfortop错误documentblob
2条回答

由于您在文章中没有指定,我不知道元组值之间的分隔符是哪个,所以我添加了一个'\n'。您可以将其更改为' '或您想要的任何内容。

final = open("tfidf.csv", "w").write('\n'.join('%s, %s' % x for x in sorted_words))

试试这个。

sorted_words = ''.join(sorted(scores.items(), reverse=True))

相关问题 更多 >