【问题标题】:Removing in-field quotes in csv file删除 csv 文件中的现场引号
【发布时间】:2012-08-14 04:24:09
【问题描述】:

假设我们有一个逗号分隔的文件 (csv),如下所示:

"name of movie","starring","director","release year"
"dark knight rises","christian bale, anna hathaway","christopher nolan","2012"
"the dark knight","christian bale, heath ledger","christopher nolan","2008"
"The "day" when earth stood still","Michael Rennie,the 'strong' man","robert wise","1951"
"the 'gladiator'","russel "the awesome" crowe","ridley scott","2000"

从上面可以看出,在第 4 行和第 5 行中,引号中有引号。 输出应如下所示:

"name of movie","starring","director","release year"
"dark knight rises","christian bale, anna hathaway","christopher nolan","2012"
"the dark knight","christian bale, heath ledger","christopher nolan","2008"
"The day when earth stood still","Michael Rennie,the strong man","robert wise","1951"
"the gladiator","russel the awesome crowe","ridley scott","2000"

如何去除出现在 csv 文件中的此类引号中的此类引号(单引号和双引号)。请注意,单个字段中的逗号是可以的,因为解析器会识别它在引号内并将其作为一个字段。这只是安排 csv 文件的预处理步骤,以便可以将其输入多个解析器以转换为我们想要的任何格式。 Bash、awk、python 都可以。请不要 perl,我厌倦了那种语言:D 提前致谢!

【问题讨论】:

  • 我不明白删除第一个和最后一个引号会有什么帮助。要求是在 csv 文件中的每个字段周围都有双引号。如果我们在每个字段之间没有引号,则无法解析其中包含逗号的字段值。
  • 我的想法是 CSV 阅读器将无法解析该文件,因为存在未转义的双引号。我想你必须自己解析它,因此我的建议。尽管无论如何它们都会被删除,但删除第一个和最后一个引号是不必要的。我以为你已经在使用 csv 模块了……我猜不是。
  • 我不明白为什么我的问题是 -1 :/
  • @crazyim5:虽然我不能确定,但​​有些人经常否决 OP 没有显示已经完成的工作的问题(在相关的情况下)。最好(比如说)发布一个您尝试过的awk 解决方案,并询问一个具体问题,说明为什么它没有按照您的意愿行事。
  • 我对在 stackoverflow 上发帖还很陌生,我会记住这一点并从下次开始。

标签: python parsing csv awk quotes


【解决方案1】:

怎么样

import csv

def remove_quotes(s):
    return ''.join(c for c in s if c not in ('"', "'"))

with open("fixquote.csv","rb") as infile, open("fixed.csv","wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, quoting=csv.QUOTE_ALL)
    for line in reader:
        writer.writerow([remove_quotes(elem) for elem in line])

产生

~/coding$ cat fixed.csv 
"name of movie","starring","director","release year"
"dark knight rises","christian bale, anna hathaway","christopher nolan","2012"
"the dark knight","christian bale, heath ledger","christopher nolan","2008"
"The day when earth stood still","Michael Rennie,the strong man","robert wise","1951"
"the gladiator","russel the awesome crowe","ridley scott","2000"

顺便说一句,您可能需要检查其中一些名称的拼写。

【讨论】:

  • if c not in ('"', "'") 也可以写成if c not in """"'""" :)
  • 啊,我本以为读者会被那些未转义的双引号窒息。
  • @TimPietzcker:重!好吧,'"'"'" 也可以工作,如果是这样的话,这要归功于字符串文字连接。 :^)
  • 效果很好!非常感谢! :)
  • 我做到了。谢谢指导。
【解决方案2】:

使用 awk,您可以执行以下操作:

awk -v Q='"' '{ gsub("[\"']","") ; gsub(",",Q "," Q) ; print Q $0 Q }'

【讨论】:

  • 感谢您的解决方案。我认为 DSM 发布的 python 解决方案效果很好。
【解决方案3】:

将值拆分为数组。遍历数组,删除除第一个和最后一个字符之外的所有引号。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2014-05-29
    • 1970-01-01
    • 2022-01-20
    • 2016-05-10
    • 2018-07-27
    相关资源
    最近更新 更多