我正在尝试拆分逗号分隔的字符串,其中字段可能或 可能不会在他们周围加上引号。
有没有办法将引号定义为可选?
以下代码仅适用于引用字段。 我正在使用python 2.7.11
import csv
temp = '"HELLO,WORLD",HELLO WORLD,END OF THE WORLD'
for i in csv.reader(temp):
print('#next#')
print(i)
输出
#next
['HELLO,WORLD']
#next#
['', '']
#next#
['H']
#next#
['E']
...
期待的是
#next
['HELLO,WORLD']
#next
['HELLO WORLD']
#next
['END OF THE WORLD']
答案 0 :(得分:1)
来自csv module文档:
csv.reader(csvfile, dialect='excel', **fmtparams)
Return a reader object which will iterate over lines in the given csvfile.
csvfile can be any object which supports the iterator protocol and
returns a string each time its next() method is called ..
因此,您需要将字符串列表传递给csv.reader
来电
为了得到正确的输出。
temp = ['"HELLO,WORLD",HELLO WORLD,END OF THE WORLD']