B A B A - 9 months ago 51
Ruby Question

How to convert command line output from Freeling to consumable array

I am using Ruby for this.
Freeling (a NLP tool) has a shallow parser which returns a string like this for the text "I just read the book, the grasshopper lies heavy" when I run a shallow parsing command.

a = <<EOT
+(I i PRP -)
+(just just RB -)
+(read read VB -)
(the the DT -)
(book book NN -)
+(The_Grasshopper_Lies_Heavy the_grasshopper_lies_heavy NP -)
+(. . Fp -)


I want to get the following array from this:

["I", "just", "read", "the book The Grasshopper Lies Heavy","."]

(I want to merge the words that are under a tree and have it as a single array element.)

So far, I have written this much:

b = a.gsub(/.*\[/,'[').gsub(/.*\+?\((\w+|.) .*/,'\1').gsub(/\n| /,"").gsub("_","")

which returns

[[I][just][read][the[book[The Grasshopper Lies Heavy]]][.]]

So, how can i get the desired array?

Answer Source

From your solution so far:

result = a.gsub(/.*\[/,'[').gsub(/.*\+?\((\w+|.) .*/,'\1').gsub(/\n| /,"").gsub("_"," ")
result.split('][').map { |s| s.gsub(/\[|\]/, ' ').strip }     # ["I", "just", "read", "the book The Grasshopper Lies Heavy", "."]