从CSV fi数据中切片每行

2024-09-21 03:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个电影数据集,看起来像这样:

1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy
2,Jumanji (1995),Adventure|Children|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama|Romance
5,Father of the Bride Part II (1995),Comedy
6,Heat (1995),Action|Crime|Thriller
7,Sabrina (1995),Comedy|Romance
8,Tom and Huck (1995),Adventure|Children

我只想提取最后一部分(类型部分,例如冒险|动画|儿童|喜剧|幻想),并将它们存储在列表[Adventure, Animation, Children, Comedy, Fantasy]。然而,我仍然停留在切片步骤。我不知道怎么做,因为line[:-1]不切片。我使用python2.7

with open(path + 'movie.csv') as f:
    for line in f:
        print line[:-1]

Tags: 数据电影line切片oldfantasychildrentoy
2条回答

切片将返回每行的最后一个字符,因为当您以常规方式读取文件时,这些行不会被拆分。您应该使用csv模块读取文件,该模块使用','分隔符自动分隔行。然后用|分割结果。你知道吗

import csv
with open(path + 'movie.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row[-1].split('|'))
with open(path + 'movie.csv') as f:
    for line in f:
        print line.split(',')[:-1].rstrip('\n').split('|')

相关问题 更多 >

    热门问题