-2

我有一个看起来像这样的字符串:

 text = "Text1 Text2 Text3 Text4 Text5\n
         Here comes more test text\n
         and even more1 more2 more3\n
         tex text textt te tex\n
         1 2 3 4 5
         ..."

如您所见,数据由一个空格字符分隔(并且一行中正好有 5 个“文本”(我的意思是字符串)。我想写一个 CSV 表来使数据看起来不错。所以它看起来像那:

 Col1    2     3     4     5
 Text1 Text2 Text3 Text4 Text5
 Here  comes more  test  text
 and   even  more1 more2 more3
 tex   text  textt te    tex
 1     2     3     4     5

应该有 5 列,每个字符串都应该在一个单元格中。我怎样才能做到这一点?

4

2 回答 2

1

你试试这个

text = "Text1 Text2 Text3 Text4 Text5\n\
Here comes more test text\n\
and even more1 more2 more3\n\
tex text textt te tex\n\
1 2 3 4 5"
filecsv = open('csvfile.csv', 'w+')
filecsv.write(text.replace(' ', ';'))
filecsv.close()
于 2013-01-26T18:02:26.627 回答
1

此代码会将数据写入csv文件。

text = """Text1 Text2 Text3 Text4 Text5\n
         Here comes more test text\n
         and even more1 more2 more3\n
         tex text textt te tex\n
         1 2 3 4 5"""

data = [x.strip() for x in text.split("\n") if x.strip() != ""]

columns = ["Col1", "2", "3", "4", "5"]

# Write dictionary list to file
outfile = "d2.csv"

with open(outfile, "w") as fp:
    for key in columns:
        fp.write(key + ", ")

    fp.write("\n")

    for line in data:
        l = ", ".join(line.split())
        print l
        fp.write(l)
    fp.write("\n")

输出:

Col1, 2, 3, 4, 5, 
Text1, Text2, Text3, Text4, Text5
Here, comes, more, test, text
and, even, more1, more2, more3
tex, text, textt, te, tex
1, 2, 3, 4, 5
于 2013-01-26T18:03:29.167 回答