【问题标题】:Create comma separated list from string but ignore commas within double quotes [duplicate]从字符串创建逗号分隔列表,但忽略双引号内的逗号 [重复]
【发布时间】:2021-08-24 18:46:49
【问题描述】:

我正在尝试从以逗号分隔的字符串创建一个列表,但在引号中包含的字符串中有一组值也包括逗号。我想创建一个忽略引号内逗号的列表。我有几百个这种格式的文本文档。这是(其中之一)字符串:

str = ('1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,')

我想要得到的结果列表是:

['1ATB', '"300, 2986, 4151, 3719, 3488, 3027, 3123, 3348, 3530"', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']

我的第一次尝试:

str=('1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,')
list1 = str.split(",")

产生以下结果:

['1ATB', '"300', '2986', '4151', '3719', '3488', '3027', '3123', '3348', '3530"', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']

感谢您对此提出的任何建议。

【问题讨论】:

  • 看看shlex.split() 以尊重报价。
  • 你听说过正则表达式吗?
  • @Drdilyor,我实际上不会认为这是一个好的正则表达式候选者。并非所有语言都是regular languages
  • @Durren, ...另外,这看起来像您正在尝试解析 CSV。只需使用 Python 的内置 CSV 解析器。
  • 我尝试了一些 CSV 方法,但没有得到我想要的格式。不过我会进一步研究。

标签: python python-3.x


【解决方案1】:

也许CSV module 可以提供帮助。

>>> s = ('1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,')
>>> print(s)
1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,
>>> from io import StringIO
>>> import csv
>>> f = StringIO(s)
>>> reader = csv.reader(f)
>>> row = next(reader)
>>> row
['1ATB', '300,2986,4151,3719,3488,3027,3123,3348,3530', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']
>>> row2 = [f'"{col}"' if ',' in col else col for col in row]
>>> row2
['1ATB', '"300,2986,4151,3719,3488,3027,3123,3348,3530"', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']
>>>

【讨论】:

  • 这非常有用,谢谢贾斯汀。有没有办法用这种方法在最终结果中保留双引号?
  • 查看编辑后的答案。
猜你喜欢
  • 1970-01-01
  • 2011-12-25
  • 2020-04-05
  • 2020-08-03
  • 2012-07-12
  • 1970-01-01
相关资源
最近更新 更多