写入文件,添加额外的 Space

Writing to a File, Adding an Additional Space

我正在创建一个生成俳句的马尔可夫文本生成器。 生成俳句的函数本身将使用 for 循环生成 100 句俳句。它们可能看起来像:

第 1 行 2号线 3号线 第一行 2号线 3号线 第一行 2号线 第 3 行

当我尝试将这些行写入文件时,我想在每个俳句之间包含一个 space,所以它看起来像:

line1
line2
line3 

line1
line2
line3

line1
line2
line3

如何在写入文件时实现这一点?

此外,有时它不会保留格式... 有时,它写成 line1line2line3

我将如何构建我的循环?

我试过:

def writeToFile():
    with open("results.txt", "w") as fp:
        count = 0
        for haiku in haikuList:
            for line in haiku:
                for item in line:
                    fp.write(str(item))
                    count += 1
        print "There are", count, "lines in your file."

俳句列表看起来像:

[[line1,
  line2,
  line3],
 [line1,
  line2,
  line3],
 [line1,
  line2,
  line3],
 [line1,
  line2,
  line3]]

for line循环之后放一个fp.write("\n");这将在每个俳句的末尾添加一个空行。

如果您需要在每一项后添加space,您可以在fp.write(str(item))后添加fp.write(" ")

假设您的俳句列表中的每个俳句都是 strunicodelist,您可以更简洁地执行类似的操作。

def writeToFile():
    with open("results.txt", "w") as fp:
        count = 0
        for haiku in haikuList:
            fp.write(" ".join(haiku) + "\n"):
            count += len(haiku)
        print "There are", count, "lines in your file."

像这样使用str.join()

def writeToFile():
    with open("results.txt", "w") as fp:
        fp.write('{}\n'.format('\n\n'.join(['\n'.join(haiku) for haiku in haikuList])))
        print "There are {} lines in your file.".format(len(haikuList)*3 + len(haikuList)-1)

这将打印每个俳句的每一行,由一个换行符分隔。 str.join() 也用于在每个俳句之间添加新行。用 file.write() you need to add in the new line if you want it, so I have used str.format() 来做到这一点。

最后,写入文件的行数等于 haikuList 的长度乘以 3 再加上每个俳句之间的新行 len(haikuList) - 1,所以你不需要不需要计数器。

还有一件事,而不是访问函数外部的变量,您应该将俳句列表传递给 writeToFile() 函数:

def writeToFile(haikuList):
    with open("results.txt", "w") as fp:
        fp.write('{}\n'.format('\n\n'.join(['\n'.join(haiku) for haiku in haikuList])))
        print "There are {} lines in your file.".format(len(haikuList)*3 + len(haikuList)-1)

然后这样称呼它:

writeToFile(haikuList)