【问题标题】:TypeError: must be str, not listTypeError:必须是 str,而不是 list
【发布时间】: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))

标签: python csv tf-idf


【解决方案1】:

试试这个。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 在文件中保存数据时出现问题。共有三个文档,只有最后一个文档保存在文件中。
    • 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] 在这几行代码之后,剩下的代码在上面提到.
    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多