如何将字符串拆分成列 [英] How to split string into column
问题描述
我有一个包含一些数据的 csv
文件,我想拆分这些数据。
I got a csv
file with some data, and I want to split this data.
一个包含一个标题,我的列2包含一些日期,我的列3包含一些链接到日期的文本。
My column one contains a title, my column 2 contains some dates, and my column 3 contains some text linked to the dates.
p>
I want to transform that in something like :
title 0 Date 0.1 text 0.1
title 0 Date 0.2 text 0.2
title 1 date 1.0 text 1.0
title 1 date 1.1 text 1.1
我如何做?
推荐答案
如果我理解你的权利,你有一个csv文件,看起来像这样:
If I understand you right, you have a csv file which looks like this:
title1,date1,text1
title2,date2,text2
title3,date3,text3
如果要拆分行,只需使用 .split()
- 函数。
If you want to split the rows, simply use the .split()
-function.
在这种情况下,它看起来类似于:
In this case, it'd look similar to this:
columns = row.split(',')
.split()
函数返回一个包含字符串的数组,因此,如果要访问列1,则必须说列[0]
。
The .split()
-function returns an array full of strings, therefore, if you want to access column 1, you have to say columns[0]
.
如果是第一行, columns [0]
会给我上面的数据 title1
。
If it's the first row, columns[0]
would give you title1
with my data above.
另一个示例:
filename = 'data.txt'
lines = [line.strip() for line in open(filename)]
for row in lines:
columns = row.split(',')
print ' '.join(columns)
使用此代码以下输出:
title1 date1 text1
title2 date2 text2
title3 date3 text3
这篇关于如何将字符串拆分成列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!