【问题标题】:How to write Strings to a CSV file in Python by making 2 columns?如何通过制作 2 列将字符串写入 Python 中的 CSV 文件?
【发布时间】:2019-11-09 06:09:46
【问题描述】:

假设我有一个loop,它的执行方式如下:-

    for i in range(len(X_test)):
      _, _, ref, hyp = result([X_test[i]],y_test.iloc[i])
      hyp = hyp.replace('<end>', '')
      bleu_score = bleu([ref], hyp, smoothing_function=cc.method3)
      print("Associated BLEU score:",bleu_score,"\n")
      overall_bleu.append(bleu_score)

我想做的是创建一个新的 CSV 文件,其中包含 2 列,即 Reference (Stands for ref variable in the loop)Predicted (Stands for hyp variable in the loop),这样对于每一行,在循环的每次连续迭代中,字符串 hypref被写入新 CSV 文件(我想创建)的相应列。有什么干净的方法吗?我在考虑使用Pandas,但似乎每次在循环中都写是多余的。

【问题讨论】:

  • 你可以使用模块csv来创建csv文件。您可以在for 循环之前打开文件并将单行写入/附加到for 循环内的文件。如果您有简单的字符串(没有逗号或输入),那么您甚至可以打开普通文本文件并使用逗号将行作为文本写入/追加并输入 - 这样您还可以创建 csv 文件。

标签: python string pandas csv io


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2016-06-15
    • 2015-07-16
    相关资源
    最近更新 更多