Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python - How to split string into column

I got a csv file with some data, and I want to split this data.

My column one contains a title, my column 2 contains some dates, and my column 3 contains some text linked to the dates.

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

How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand you right, you have a csv file which looks like this:

title1,date1,text1
title2,date2,text2
title3,date3,text3

If you want to split the rows, simply use the .split()-function.

In this case, it'd look similar to this:

columns = row.split(',')

The .split()-function returns an array full of strings, therefore, if you want to access column 1, you have to say columns[0].

If it's the first row, columns[0] would give you title1 with my data above.


Another example:

filename = 'data.txt'
lines = [line.strip() for line in open(filename)]
for row in lines:
    columns = row.split(',')
    print ' '.join(columns)

Using this code, gives you the following output:

title1 date1 text1
title2 date2 text2
title3 date3 text3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...