【问题标题】:How to execute OpenRefine JSON on CSV in Python?如何在 Python 中的 CSV 上执行 OpenRefine JSON?
【发布时间】:2017-07-29 11:04:54
【问题描述】:

我正在尝试找到一个 Python 解决方案,它可以在没有打开 OpenRefine 服务器的情况下以 JSON 格式执行以下 OpenRefine Python 命令。 我的OpenRefine JSON 在任何格式正确的 CSV 文件的每个字段上都包含映射和自定义 Python 命令,因此这不是基本的 JSON 读取。 一个示例 OpenRefine JSON 代码,其中只有正则表达式映射

[
  {
    "op": "core/text-transform",
    "description": "Text transform on cells in column Sleep using expression jython:import re\n\nvalue = re.sub(\"h0\", \"h\",value)\n\nvalue = re.sub(\"h\",\"*60+\", value)\n\nreturn eval(value)\n\n \nreturn eval(value.replace(\"h\", \"*60+\"));",
    "engineConfig": {
      "mode": "row-based",
      "facets": []
    },
    "columnName": "Sleep",
    "expression": "jython:import re\n\nvalue = re.sub(\"h0\", \"h\",value)\n\nvalue = re.sub(\"h\",\"*60+\", value)\n\nreturn eval(value)\n\n \nreturn eval(value.replace(\"h\", \"*60+\"));",
    "onError": "keep-original",
    "repeat": false,
    "repeatCount": 10
  }
]

一种解决方案是对每种类型的元素逐个处理 JSON,但使用某些包可能会有更简单的解决方案。

Python:3.5.2
操作系统:Debian 9

【问题讨论】:

    标签: python json csv openrefine


    【解决方案1】:

    pyrefine 项目旨在做到这一点。但它仍在进行中,支持的操作很少。欢迎投稿!

    【讨论】:

    • 知道R中是否存在与pyrefine相同的解决方案吗?我发现的大多数包都是用于客户端和 OpenRefine 服务器之间的双工通信。
    • 只是,我完全忘记了这个项目的存在!
    • @hhh 完全不知道,对不起!我同意,这在 R 中也很有意义。
    【解决方案2】:

    我不知道任何现成的解决方案,也不知道该怎么做。一种解决方法可能是尝试将 Jython 脚本转换为函数,然后使用 pandas 将它们应用到您的 csv。

    import json
    import re
    
    with open("your open refine json", "r") as infile:
        data = json.load(infile)
    
    with open("result.py", 'w') as outfile:
        for el in data:
            count = 1
            column=el['columnName']
            expression = el['expression'].replace("jython:", "")
            expression = re.sub(r"\n\n\s?\n?", "\n    ", expression)
            expression = re.sub(r";$", "", expression)
            result = """def function%s(value):\n    %s""" %(count, expression)
            count+=1
            outfile.write(result + 
                          "\n\n" + 
                          "mycsv['%s'] = mycsv['%s'].apply(lambda x: function%s(x))" %(column, column, count-1))
    

    Json 的结果:

    def function1(value):
        import re
        value = re.sub("h0", "h",value)
        value = re.sub("h","*60+", value)
        return eval(value)
        return eval(value.replace("h", "*60+")) # is this second return an error ?
    
    mycsv['Sleep'] = mycsv['Sleep'].apply(lambda x: function1(x))
    

    最后,您可以在result.py 的顶部添加这些行,启动脚本,然后祈祷...

    import pandas as pd 
    
    mycsv = pd.read_csv("your csv", encoding = "utf8")
    

    【讨论】:

      【解决方案3】:

      我发现了多种不同的选择。我试图判断他们是否有其他选择。 Pyrefine 是迄今为止唯一真正的 Python 解决方案。

      替代方案

      我。部分解决方案here 使用 Python 在 R 中创建字典以进行转换。这不会实现 GREPL 编辑、Jython/Python 编辑或 Closure 编辑。

      #!/usr/bin/env python2
      #
      # Description
      #      This builds a dictionary-style structure to R with Python
      #      to do the JSON edits on other data, with only `Cluster-edit` support.    
      #
      #      The original source is (1) on which I have done some remarks.
      #
      # Further reading
      #
      # (1) Original source of the code, https://medium.com/optima-blog/semi-automated-text-cleaning-in-r-68054a9491da
      import json
      import sys
      import os
      if len(sys.argv) < 2:
       print “USAGE: ./utils/open_refine_to_R.py [edits.json] > r_file.R”
       exit(1)
      json_file = sys.argv[-1]
      #conversions = json.load(open(“state_clustering.json”))
      conversions = json.load(open(json_file))
      function_name = os.path.splitext(os.path.basename(json_file))[0]
      print “%s = function(df) {“ %function_name
      for conv in conversions:
      
        #THIS WILL fire ERRORS WITHOUT try-catch eg. with regexes
        edits = conv[‘edits’]
      
        columnName = str(conv[‘columnName’])
        for edit in edits:
          froms = edit[‘from’]
          to = edit[‘to’]
          for source in froms:
            source = str(source)
            to = str(to)
            print “ df[df[, %s] == %s, %s] = %s” %(repr(columnName),
              repr(source), repr(columnName), repr(to))
      print “ df”
      print “}”
      

      可以将输出编辑为 Python 格式。

      二。 P3-batchrefine 主要是用 Java 编写的,但也有一些 Python 代码。它让您可以通过以下方式进行转换(不是真正的 Python 解决方案,除非您可以很好地调用外部 Java 库)。

      ./bin/batchrefine remote input.csv transform.json > output.csv

      三。 Pyrefine 是一个真正的 python 解决方案,它旨在以下列方式工作,从其文档中复制:

      import pyrefine
      import pandas as pd
      
      with open('script.json') as script_file:
          script = pyrefine.parse(script_file)
      
      input_data = pd.read_csv('input.csv')
      output_data = script.execute(input_data)
      

      解析 OpenRefine JSON 的更多信息

      1. Trying to parse a Json with Open Refine GREL

      2. Parse JSON in Google Refine

      3. Best way to parse a big and intricated Json file with OpenRefine (or R)

      【讨论】:

      • 相关票证:github.com/OpenRefine/OpenRefine/issues/1220 效果够好吗?
      • @LéoLéopoldHertz준영 当然,但它不能作为直接的 R 函数访问。你必须使用 Python 作为中间步骤来获得 R 的东西。
      【解决方案4】:

      这里有一些额外的项目:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-28
        • 2017-08-17
        • 1970-01-01
        • 1970-01-01
        • 2017-05-20
        • 2018-07-26
        • 1970-01-01
        • 2020-12-19
        相关资源
        最近更新 更多