当元素包含逗号时如何在 python 中创建列表
How to create a list in python when the elements contain commas
如何在 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 文件的工具...你应该使用它们
print list(csv.reader(open("outfile.csv","r")))
也许吧?
在第一个逗号后停止拆分:
line = i.strip().split(",", 1)
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']
如何在 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 文件的工具...你应该使用它们
print list(csv.reader(open("outfile.csv","r")))
也许吧?
在第一个逗号后停止拆分:
line = i.strip().split(",", 1)
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']