我希望下面的代码避免在双引号内拆分,但它确实做到了:

import csv
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";
"""

for l in csv.reader(StringIO(contents), delimiter=";", quotechar='"', skipinitialspace=True, quoting=csv.QUOTE_MINIMAL):
    print(l)

输出:

['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"', '']

您可以看到它在双引号内拆分,因此note "putative; transgelin 2"变成['note "putative', 'transgelin 2'].我该怎么解决这个问题?

推荐答案

对于shlex人来说,这似乎是一个很好的用法:

import shlex
​
lexer = shlex.shlex(contents, posix=True)
lexer.whitespace_split = True
lexer.whitespace = ";"
​
out1 = [e.strip() for e in lexer if e.strip() != ""]

或者,如果你想保留引号,你可以用split:

import re

out2 = [e.strip() for e in re.split(r'(?<=")\s*;\s*', contents) if e != ""]

发帖主题:Re:Kolibrios

print(out1)

['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']

print(out2)

['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"']

Python相关问答推荐

如何使用上下文管理器创建类的实例?

Pandas :多索引组

在Python和matlab中显示不同 colored颜色 的图像

具有多个选项的计数_匹配

韦尔福德方差与Numpy方差不同

不理解Value错误:在Python中使用迭代对象设置时必须具有相等的len键和值

管道冻结和管道卸载

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

django禁止直接分配到多对多集合的前端.使用user.set()

如何在给定的条件下使numpy数组的计算速度最快?

部分视图的DataFrame

如何在UserSerializer中添加显式字段?

根据列值添加时区

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

使用特定值作为引用替换数据框行上的值

Flask Jinja2如果语句总是计算为false&

如何在Python中使用Iscolc迭代器实现观察者模式?

Python 3试图访问在线程调用中实例化的类的对象

统计numpy. ndarray中的项目列表出现次数的最快方法

合并相似列表