【问题标题】:How to create a list in python when the elements contain commas当元素包含逗号时如何在python中创建列表
【发布时间】:2015-12-06 02:08:22
【问题描述】:

如何在 python 中创建一个字符串列表,其中字符串可以包含逗号,这样解释器就不会过早地中断逗号。

我正在阅读由 MSExcel 创建的模板 csv 文件。内容为 2 列:col1 = 颜色,col2 = 可以包含逗号的句子。内容如下:

Light Green,"Matches type, instance, etc."
Red,Happens in BD10 but not BD20
Blue,"Instance and time matches, type doesn't match"
Yellow,Caught on replay

当我读入并输出所读内容时,它会在所有逗号上打断输入行。

#my code snippet, please excuse any typos during sanitization
with open('outfile.csv','r') as infile:
   blah = infile.readlines()
   for i in blah:
      line = i.strip().split(",")
      print line

My output:
['Light Green', '"Matches type', ' instance', ' etc."']
['Red', 'Happens in BD10 but not BD20']
['Blue', '"Instance and time matches', ' type doesn\'t match"']
['Yellow', 'Caught on replay']

我如何告诉 python 在 "" 内忽略逗号并在所有其他时间以逗号分隔?

【问题讨论】:

    标签: python csv comma


    【解决方案1】:

    python 提供了解析 csv 文件的工具……你应该使用它们

    print list(csv.reader(open("outfile.csv","r")))
    

    也许?

    【讨论】:

      【解决方案2】:

      在第一个逗号后停止拆分:

      line = i.strip().split(",", 1)
      

      【讨论】:

      • @brent Washburne,这个解决方案很酷。为了全面起见,如果句子在 col1 中并且颜色在 col2 中,我将如何告诉 python 不要在句子中用逗号打断,因为由于逗号不在第一次出现中,你的技巧将不起作用?
      【解决方案3】:

      cvs module 让这一切变得简单。

      给定:

      $ cat /tmp/so.csv
      Light Green,"Matches type, instance, etc."
      Red,Happens in BD10 but not BD20
      Blue,"Instance and time matches, type doesn't match"
      Yellow,Caught on replay
      

      试试:

      import csv
      with open('/tmp/so.csv') as f:
          for line in csv.reader(f):
              print line    
      

      打印:

      ['Light Green', 'Matches type, instance, etc.']
      ['Red', 'Happens in BD10 but not BD20']
      ['Blue', "Instance and time matches, type doesn't match"]
      ['Yellow', 'Caught on replay']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-12
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        • 1970-01-01
        相关资源
        最近更新 更多