From d92209e3ec223a380c7ad540622caa15712c490c Mon Sep 17 00:00:00 2001 From: Patrick Simianer Date: Wed, 18 Jun 2014 08:28:36 +0200 Subject: better integration, chart.to_json --- parse.rb | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) (limited to 'parse.rb') diff --git a/parse.rb b/parse.rb index 8005401..b39b456 100644 --- a/parse.rb +++ b/parse.rb @@ -16,6 +16,7 @@ end class Chart def initialize n + @n = n @m = [] (n+1).times { a = [] @@ -38,8 +39,48 @@ class Chart return @b["#{i},#{j},#{symbol}"] end - def to_json - #TODO + def to_json weights=nil + id = 0 + json_s = "{\n" + json_s += "\"weights\":#{weights.to_json},\n" + json_s += "\"nodes\":\n" + json_s += "[\n" + seen = {} + Parse::visit(1, 0, @n) { |i,j| + self.at(i,j).each { |item| + _ = "#{item.lhs.symbol},#{i},#{j}" + if !seen[_] + json_s += "{ \"id\":#{id}, \"cat\":\"#{item.lhs.symbol.to_json.slice(1..-1).chomp('"')}\", \"span\":[#{i},#{j}] },\n" + seen[_] = id + id += 1 + end + } + } + json_s += "{ \"id\":-1, \"cat\":\"root\", \"span\":[-1, -1] }\n" + json_s += "],\n" + json_s += "\"edges\":\n" + json_s += "[\n" + a = [] + Parse::visit(1, 0, @n) { |i,j| + self.at(i,j).each { |item| + _ = '{ ' + _ += "\"head\":#{seen[item.lhs.symbol+','+i.to_s+','+j.to_s]}, " + _ += "\"rule\":\"[#{item.lhs.symbol.to_json.slice(1..-1).chomp('"')}] ||| " + _ += "#{item.rhs.map{|x| (x.class==Grammar::NT ? '['+x.symbol.to_json.slice(1..-1).chomp('"')+','+x.index.to_s+']' : x.word.to_json).slice(1..-1).chomp('"') }.join(' ')} ||| #{item.target.map{|x| (x.class==Grammar::NT ? '['+x.symbol.to_json.slice(1..-1).chomp('"')+','+(x.index+1).to_s+']' : x.word.to_json.slice(1..-1).chomp('"')) }.join(' ')}\ |||\", " + if item.tail_spans.empty? + _ += "\"tails\":[-1], " + else + _ += "\"tails\":[#{item.rhs.zip((0..item.rhs.size-1).map{|q| item.tail_spans[q] }).select{|x| x[0].class==Grammar::NT }.map{|x| seen[x[0].symbol.to_json.slice(1..-1).chomp('"')+','+x[1].left.to_s+','+x[1].right.to_s]}.join ', '}], " + end + _ += "\"f\":#{(item.f ? item.f.to_json : '{}')} }" + a << _ + } + } + json_s += a.join ",\n" + json_s += "\n]\n" + json_s += "}\n" + + return json_s end end -- cgit v1.2.3