我正在努力分割文本行,基于变量分隔符,并保留空字段和引用的数据.
例子:
1,"2",three,'four, 4',,"6\tsix"
或作为制表符分隔的vesion
1\t"2"\tthree\t'four, 4'\t\t"6\tsix"
都应该导致:
['1', '"2"', 'three', 'four, 4', '', "6\tsix"]
到目前为止,我已经尝试过:
>使用split,但是明确地说,引用的分隔符不按需要处理.
>使用csv库的解决方案,但它倾向于具有引用全部或全部内容的选项,而不保留原始引号.
>正则表达式,特别是从以下答案的模式,但它删除空字段:How to split but ignore separators in quoted strings, in python?
>使用pyparsing库.我管理的最好的是如下,但这也会删除空字段(使用逗号分隔符示例):
s = '1,"2",three,\'four, 4\',,"6\tsix"'
wordchars = (printables + ' \t\r\n').replace(',', '', 1)
delimitedList(OneOrMore(quotedString | Word(wordchars)), ',').parseWithTabs().parseString(s)
感谢任何想法!