【问题标题】:Python: How to split a string with csv reader that has optional quotesPython:如何使用具有可选引号的 csv 阅读器拆分字符串
【发布时间】:2016-12-27 09:28:28
【问题描述】:

我正在尝试拆分一个逗号分隔的字符串,其中字段 可能可能没有有引号。

有没有办法将引号定义为可选

以下代码仅适用于带引号的字段。 我正在使用 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']    

【问题讨论】:

  • 只需将[temp] 传递给csv.reader 调用
  • 谢谢。那太容易了!如果您将其发布为答案,我会接受。

标签: python-2.7 csv


【解决方案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']

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2013-02-24
    • 2013-06-19
    • 1970-01-01
    • 2019-07-08
    • 2015-04-11
    相关资源
    最近更新 更多