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

如何解决csv模块解析CSV时引号内内容被错误拆分的问题?

修复双引号内内容被拆分的问题

你的问题出在输入格式不符合标准CSV规范,同时csv模块的参数配置不对:

  • 标准CSV要求包含分隔符的整个字段用引号包裹,而你的格式是key "value_with_semicolon";,仅字段内的value部分加引号,导致csv.reader将引号内的分号识别成分隔符。
  • 你使用的quoting=csv.QUOTE_MINIMAL仅会对包含分隔符/引号的字段添加引号,但不会忽略引号内的分隔符。

以下是两种可行的修复方案:

方案1:使用正则表达式拆分(推荐)

直接用正则匹配不在双引号内的分号作为分隔符,无需依赖csv模块的严格格式要求:

import re
from io import StringIO

contents = """
gene "Tagln2"; note "putative; transgelin 2 (MGD|MGI:1312985 GB|BC049861, evidence: BLASTN, 99%, match=1379)"; product "transgelin-2"; protein_id "NP_848713.1"; tag "RefSeq Select"; exon_number "4";
"""

# 匹配不在双引号内的分号
split_pattern = re.compile(r';(?=(?:[^"]*"[^"]*")*[^"]*$)')

for line in StringIO(contents):
    line = line.strip()
    if not line:
        continue
    # 拆分后去除每个元素的首尾空格,同时移除末尾空元素
    parts = [part.strip() for part in split_pattern.split(line) if part.strip()]
    print(parts)

输出结果:

['gene "Tagln2"', 'note "putative; transgelin 2 (MGD|MGI:1312985 GB|BC049861, evidence: BLASTN, 99%, match=1379)"', 'product "transgelin-2"', 'protein_id "NP_848713.1"', 'tag "RefSeq Select"', 'exon_number "4"']

方案2:预处理字符串适配标准CSV格式

先将你的自定义格式转换成标准CSV格式,再用csv模块处理:

import csv
import re
from io import StringIO

contents = """
gene "Tagln2"; note "putative; transgelin 2 (MGD|MGI:1312985 GB|BC049861, evidence: BLASTN, 99%, match=1379)"; product "transgelin-2"; protein_id "NP_848713.1"; tag "RefSeq Select"; exon_number "4";
"""

# 预处理:将 key "value" 转换为标准CSV的字段格式 "key \"value\""
processed_content = re.sub(r'(\w+) "([^"]+)"', r'"\1 \"\2\""', contents.strip())

# 用csv.reader读取,配置正确参数
for row in csv.reader(StringIO(processed_content), delimiter=";", quotechar='"', skipinitialspace=True):
    # 还原引号并过滤空元素
    cleaned_parts = [part.replace('\\"', '"').strip('"') for part in row if part]
    print(cleaned_parts)

这种方案需要额外的预处理步骤,适合必须使用csv模块的场景。

内容的提问来源于stack exchange,提问作者The Unfun Cat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:27:50