【问题标题】:Regex to remove doubled double quotes from CSV正则表达式从 CSV 中删除双引号
【发布时间】:2013-08-27 18:01:47
【问题描述】:

我有一个 excel 表,它的一列中有很多数据,以来自 sql 数据库的 python 字典的形式。我无权访问原始数据库,也无法使用本地 infile 命令将 CSV 导入 sql,因为 CSV 每一行上的键/值的顺序不同。当我将 excel 工作表导出为 CSV 时,我得到:

"{""first_name"":""John"",""last_name"":""Smith"",""age"":30}"
"{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"

去除大括号前后的“以及键/值周围多余的”的最佳方法是什么?

我还需要单独留下没有引号的整数。

我正在尝试使用 json 模块将其导入 python,以便我可以打印特定的键,但我无法使用双引号导入它们。我最终需要将数据保存在如下所示的文件中:

{"first_name":"John","last_name":"Smith","age":30}
{"first_name":"Tim","last_name":"Johnson","age":34}

非常感谢任何帮助!

【问题讨论】:

  • 这不是 CSV 格式。看起来您正在寻找 JSON。
  • 我帖子底部的数据行是每一行的excel表的列中的内容。大约有 13k 行。当我将它保存到 CSV 时,顶部就是我得到的。我想我可以使用 JSON 模块,但我需要去掉双引号。由于 CSV 格式,当我将其保存到 CSV 时,excel 会使用我现有的引号并将它们加倍。
  • 感谢您的快速建议!我必须用完,但当我返回并选择答案时会检查这些。感谢您的帮助!

标签: python sql regex excel dictionary


【解决方案1】:

简单:

text = re.sub(r'"(?!")', '', text)

给定输入文件:TEST.TXT:

"{""first_name"":""John"",""last_name"":""Smith"",""age"":30}"
"{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"

脚本:

import re
f = open("TEST.TXT","r")
text_in = f.read()
text_out = re.sub(r'"(?!")', '', text_in)
print(text_out)

产生以下输出:

{"first_name":"John","last_name":"Smith","age":30}
{"first_name":"Tim","last_name":"Johnson","age":34}

【讨论】:

    【解决方案2】:

    应该这样做:

    with open('old.csv') as old, open('new.csv', 'w') as new:
        new.writelines(re.sub(r'"(?!")', '', line) for line in old)
    

    【讨论】:

      【解决方案3】:

      如果输入文件如图所示,并且您提到的文件很小,您可以将整个文件加载到内存中,进行替换,然后保存。恕我直言,您不需要 RegEx 来执行此操作。最容易阅读的代码是:

      with open(filename) as f:
          input= f.read()
      input= str.replace('""','"')
      input= str.replace('"{','{')
      input= str.replace('}"','}')
      with open(filename, "w") as f:
          f.write(input)
      

      我用样本输入对其进行了测试,它产生了:

      {"first_name":"John","last_name":"Smith","age":30}
      {"first_name":"Tim","last_name":"Johnson","age":34}
      

      这正是你想要的。

      如果你愿意,也可以打包代码写

      with open(inputFilename) as if:
          with open(outputFilename, "w") as of:
              of.write(if.read().replace('""','"').replace('"{','{').replace('}"','}'))
      

      但我认为第一个更清晰,并且两者都完全相同。

      【讨论】:

      • @jabaldonedo str 不是保留字。否则我的程序将无法编译和运行。 str 一个内置函数,如果我不使用它,我可以重新定义它。但你是对的,这可能会令人困惑。我正在更改代码。感谢您指出并帮助使答案成为更好的答案。
      【解决方案4】:

      我觉得你这个问题想多了,为什么不替换数据呢?

      l = list()
      with open('foo.txt') as f:
          for line in f:
              l.append(line.replace('""','"').replace('"{','{').replace('}"','}'))
      s = ''.join(l)
      
      print s # or save it to file
      

      它生成:

      {"first_name":"John","last_name":"Smith","age":30}
      {"first_name":"Tim","last_name":"Johnson","age":34}
      

      使用list 存储中间行,然后调用.join 以提高性能,如Good way to append to a string 中所述

      【讨论】:

        【解决方案5】:

        您可以实际使用 csv 模块和正则表达式来执行此操作:

        st='''\
        "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}"
        "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"\
        '''
        
        import csv, re
        
        data=[]
        reader=csv.reader(st, dialect='excel')
        for line in reader:
            data.extend(line)
        
        s=re.sub(r'(\w+)',r'"\1"',''.join(data))
        s=re.sub(r'({[^}]+})',r'\1\n',s).strip()
        print s
        

        打印

        {"first_name":"John","last_name":"Smith","age":"30"}
        {"first_name":"Tim","last_name":"Johnson","age":"34"}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-13
          • 1970-01-01
          • 1970-01-01
          • 2018-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多