You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何正确拆分含内嵌逗号的逗号分隔行?

如何正确拆分含分隔符的CSV字段?

问题描述

待拆分的示例行:

1,"Rink, The (1916)",Comedy

直接用split(',')会因为标题字段里的逗号导致拆分错误:

id, title, genres = line.split(',')

期望得到的正确结果:

id = 1
title = 'Rink, The (1916)'
genres = 'Comedy'

解决方案

推荐:用Python标准库csv模块处理

CSV格式本身有规范,官方提供的csv模块能完美应对带引号包裹的含分隔符字段:

方式1:csv.reader按索引读取

import csv

line = '1,"Rink, The (1916)",Comedy'
# 将单行转为列表传入reader
reader = csv.reader([line])
for row in reader:
    id_val, title, genres = row
    print(f"id = {id_val}")
    print(f"title = '{title}'")
    print(f"genres = '{genres}'")

方式2:csv.DictReader按字段名读取

如果有表头或者想更清晰地按字段名访问,用这个更方便:

import csv

line = '1,"Rink, The (1916)",Comedy'
# 定义字段名称
field_names = ['id', 'title', 'genres']
reader = csv.DictReader([line], fieldnames=field_names)
for row in reader:
    print(f"id = {row['id']}")
    print(f"title = '{row['title']}'")
    print(f"genres = '{row['genres']}'")

手动解析(不推荐)

如果不想依赖标准库,也可以手动定位引号位置拆分,但这种方法通用性差,容易出错:

line = '1,"Rink, The (1916)",Comedy'
start_q = line.index('"')
end_q = line.rindex('"')

id_val = line[:start_q-1]
title = line[start_q+1:end_q]
genres = line[end_q+2:]

print(f"id = {id_val}")
print(f"title = '{title}'")
print(f"genres = '{genres}'")

内容的提问来源于stack exchange,提问作者Volodymyr K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:15:53