Python分隔线分裂问题

use*_*203 9 python regex csv split pyparsing

我正在努力根据变量分隔符拆分文本行,并保留空字段和引用数据.

例子:

1,"2",three,'four, 4',,"6\tsix"
Run Code Online (Sandbox Code Playgroud)

或作为制表符分隔的vesion

1\t"2"\tthree\t'four, 4'\t\t"6\tsix"
Run Code Online (Sandbox Code Playgroud)

两者都应该导致:

['1', '"2"', 'three', 'four, 4', '', "6\tsix"]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过:

  1. 使用拆分,但显然引用的分隔符未按要求处理.

  2. 使用csv库的解决方案,但它往往有选项引用一切或什么都没有,而不保留原始引号.

  3. 正则表达式,特别是遵循以下答案的模式,但它删除空字段:如何拆分但忽略引号字符串中的分隔符,在python中?

  4. 使用pyparsing库.我管理的最好的是如下,但这也会删除空字段(使用逗号分隔符示例):

    s = '1,"2",three,\'four, 4\',,"6\tsix"'
    wordchars = (printables + ' \t\r\n').replace(',', '', 1)
    delimitedList(OneOrMore(quotedString | Word(wordchars)), ',').parseWithTabs().parseString(s)
    
    Run Code Online (Sandbox Code Playgroud)

谢谢你的任何想法!

Pau*_*McG 7

这对我有用:

import pyparsing as pyp

pyp.delimitedList(pyp.quotedString | pyp.SkipTo(',' | pyp.LineEnd()), ',') \
    .parseWithTabs().parseString(s)
Run Code Online (Sandbox Code Playgroud)

['1', '"2"', 'three', "'four, 4'", '', '"6\tsix"']
Run Code Online (Sandbox Code Playgroud)

避免使用空格字符或所有可打印字符创建单词.Pyparsing没有任何前瞻性,这些表达式可能包含的内容远远超出您的计划.