如何根据引号在csv中写入值并忽略引号中的逗号?

2024-10-04 05:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个csv列表中的一些项目,这些项目是在引号和逗号之间。我如何写它们,使项目不因逗号而分开?我看了许多类似的问题,但没有找到我的问题的具体解决办法

['Saks, Lord & Taylor data breach may affect 5 million customers', (u'By Mike Murphy', u'April 1, 2018, 5:24 p.m. EST')]
['Why The China Hustle is a finance documentary all U.S. investors need to see', (u'By MarketWatch', u'NewsWatch')]
['Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets', (u'By Mike Murphy', u'April 1, 2018, 4:49 p.m. EST')]

预期答案:

first column = 'Saks, Lord & Taylor data breach may affect 5 million customers'
                'Why The China Hustle is a finance documentary all U.S. investors need to see'
                'Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets'

second column = 'By Mike Murphy' 
                'By MarketWatch'
                'By Mike Murphy'

third column =  'April 1, 2018, 5:24 p.m. EST'
                'NewsWatch'
                'April 1, 2018, 4:49 p.m. EST'

Tags: to项目databycolumnmaymikeest
2条回答

这个怎么样

next_field<-function(stream) {
  p<-seek(stream)
  d<-readChar(stream,1)
  seek(stream,p)
  if(d=="\"")    
    field<-scan(stream,"",1,sep=",",quote="\"",blank=FALSE)   
  else
    field<-scan(stream,"",1,sep=",",quote="",blank=FALSE)
  return(field)
}


s<-file("C:/your_path_here/sample.csv",open="rt")
header<-readLines(s,1)
header<-scan(what="",text=header,sep=",")
line<-replicate(length(header),next_field(s))

setNames(as.data.frame(lapply(line,type.convert)),header)

简单到:

x=[['Saks, Lord & Taylor data breach may affect 5 million customers', (u'By                                                      Mike Murphy', u'April 1, 2018, 5:24 p.m. EST')],['Why The China Hustle is a finance documentary all U.S. investors need to see', (u'By MarketWatch', u'NewsWatch')],['Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets', (u'By Mike Murphy', u'April 1, 2018, 4:49 p.m. EST')]]
import csv
with open('bla.csv','w') as fd:
    writer=csv.writer(open('bla.csv','w'))
    writer.writerows(x)

csv中没有引用“为什么中国…”,因为它不包含任何逗号。如果要引用它,可以在writer构造函数中使用quoting=QUOTE_ALL

相关问题 更多 >