如何用Python在CSV上执行OpenRefine JSON?

2024-09-28 21:51:32 发布

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

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

[
  {
    "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


Tags: import命令rejsonvalue格式evaltransform
3条回答

pyrefine项目正是为了做到这一点。但这仍然是一个正在进行的工作,很少有业务得到支持。欢迎投稿!在

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

备选方案

I.一个部分解决方案here在R中用Python创建一个字典来进行转换。这不实现GREPL编辑、Jython/Python编辑或闭包编辑。在

#!/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。它允许您以以下方式进行转换(除非您能够很好地调用外部Java库,否则不是真正的Python解决方案)。在

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

III.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)

我不知道任何现成的解决办法,我也不知道怎么做。解决方法可能是尝试将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上的结果:

^{pr2}$

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

import pandas as pd 

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

相关问题 更多 >