【问题标题】:How to Escape all Single Double Quotation Marks in Particular .csv Column with Python?如何使用 Python 转义特定 .csv 列中的所有单双引号?
【发布时间】:2018-09-27 23:17:37
【问题描述】:
  • 使用 Python 2.7.6
  • 需要不使用 Pandas 库的解决方案

我的 .csv 文件具有特定(文本)列,其单元格偶尔会包含双引号 (")。在 ArcMap 中转换为 shapefile 时,这些单双引号会导致错误转换。它们必须“转义” .

我需要一个脚本来编辑 .csv 以便它:

  1. 将“”的所有实例替换为“”。
  2. 用双引号将每个单元格括起来。

我的脚本:

import csv

with open(Source_CSV, 'r') as file1, open('OUTPUT2.csv','w') as file2:
    reader = csv.reader(file1)  

    # Write column headers without quotes
    headers = reader.next()
    str1 = ''.join(headers)
    writer = csv.writer(file2)
    writer.writerow(headers)

    # Write all other rows with quotes
    writer = csv.writer(file2, quoting=csv.QUOTE_ALL)
    for row in reader:
        writer.writerow(row)

此脚本成功完成了 ALL 列中的上述两项任务。

例如这个原始的.csv:

Column 1, Column 2, Column 3, Column 4 
Fred, Flintstone, 5'10", black hair 
Wilma, Flintstone, five feet seven inches, red hair 
Barney, Rubble, 5 feet 2" inches, blond hair 
Betty, Rubble, 5 foot 7, black hair

变成这样:

Column 1, Column 2, Column 3, Column 4
"Fred"," Flintstone"," 5'10"""," black hair"
"Wilma"," Flintstone"," five feet seven inches"," red hair"
"Barney"," Rubble"," 5 feet 2"" inches"," blond hair"
"Betty"," Rubble"," 5 foot 7"," black hair"

但是,如果我只想在 第 3 列(实际上偶尔有双引号的那一列)中完成此操作,该怎么办?

换句话说,我怎么能得到这个……?

Column 1, Column 2, Column 3, Column 4
Fred, Flintstone," 5'10""", black hair
Wilma, Flintstone," five feet seven inches", red hair
Barney, Rubble," 5 feet 2"" inches", blond hair
Betty, Rubble," 5 foot 7", black hair

【问题讨论】:

    标签: python python-2.7 csv


    【解决方案1】:

    只引用包含双引号的字段就足够了吗?如果是这样,csv 模块的默认行为将起作用,尽管我在解析输入文件时添加了skipinitialspace=True,因此它不会将逗号后面的空格视为重要。

    另外根据csv 模块文档,我已经以二进制模式打开了文件。

    import csv
    
    with open('input.csv','rb') as file1, open('output.csv','wb') as file2:
        reader = csv.reader(file1,skipinitialspace=True)  
        writer = csv.writer(file2)
    
        for row in reader:
            writer.writerow(row)
    

    输入:

    Column 1, Column 2, Column 3, Column 4
    Fred, Flintstone, 5'10", black hair
    Wilma, Flintstone, five feet seven inches, red hair
    Barney, Rubble, 5 feet 2" inches, blond hair
    Betty, Rubble, 5 foot 7, black hair
    

    输出:

    Column 1,Column 2,Column 3,Column 4
    Fred,Flintstone,"5'10""",black hair
    Wilma,Flintstone,five feet seven inches,red hair
    Barney,Rubble,"5 feet 2"" inches",blond hair
    Betty,Rubble,5 foot 7,black hair
    

    如果您需要引用第 3 列的每一行,则可以手动执行。我已将 csv 模块设置为不引用任何内容,并将引号字符设置为不应出现在输入中的不可打印控制字符:

    import csv
    
    with open('input.csv','rb') as file1, open('output.csv','wb') as file2:
        reader = csv.reader(file1,skipinitialspace=True)
        writer = csv.writer(file2,quoting=csv.QUOTE_NONE,quotechar='\x01')
    
        # Write column headers without quotes
        headers = reader.next()
        writer.writerow(headers)
    
        # Write 3rd column with quotes
        for row in reader:
            row[2] = '"' + row[2].replace('"','""') + '"'
            writer.writerow(row)
    

    输出:

    Column 1,Column 2,Column 3,Column 4
    Fred,Flintstone,"5'10""",black hair
    Wilma,Flintstone,"five feet seven inches",red hair
    Barney,Rubble,"5 feet 2"" inches",blond hair
    Betty,Rubble,"5 foot 7",black hair
    

    【讨论】:

    • 感谢您提供的两个选项。还有使用skipinitialspace的提示和使用二进制模式的提示。
    【解决方案2】:

    你可以试试这个:

        import csv
    with open("file.csv", "rU") as fin:
        words = fin.readlines()
    
    with open("cleaned.csv", "w") as fout:
        writer = csv.writer(fout, quoting=csv.QUOTE_ALL, quotechar = '"', doublequote = True)
        for row in words:
            row = row.replace("\n", "")
            newrow = []
            for word in row.split(","): 
                newrow.append(word.strip())
            writer.writerow(newrow)
    

    首先打开尝试将其作为简单文本文件读取,以绕过格式错误的 csv 文件。然后我们通常将其写入 csv 文件。

    【讨论】:

    • 谢谢。你和我的都达到了相同的结果:所有列中的所有字段都用双引号括起来,双引号加倍。但是该解决方案如何仅应用于您选择的一列?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2011-09-21
    相关资源
    最近更新 更多