B A B A - 1 year ago 73
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", "."]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download