Extract selected data from a text file in Ruby

Now I am working on extracting information from a text file in Ruby. Then how can I extract only the number "0.6748984055823062" from the following text file?

{ "sentiment_analysis": [ { "positive": [ { "sentiment": "Popular", "topic": "games", "score": 0.6748984055823062, "original_text": "Popular games", "original_length": 13, "normalized_text": "Popular games", "normalized_length": 13, "offset": 0 }, { "sentiment": "engaging", "topic": "pop culture-inspired games", "score": 0.6280145725181376, "original_text": "engaging pop culture-inspired games", "original_length": 35, "normalized_text": "engaging pop culture-inspired games", "normalized_length": 35, "offset": 370 }, 

What I tried was that I could read the file and print it line by line with the following code.

 counter = 1 file = File.new("Code.org", "r") while (line = file.gets) puts "#{counter}: #{line}" counter = counter + 1 end file.close 

I want to set a number to a variable so that I can process it.

+2
source share
2 answers

Here is a script that retrieves only the desired result.

Two things to keep in mind:

  • The rating you are looking for may not be the first.
  • data is a combination of arrays and hashes


 json_string = %q${ "sentiment_analysis": [ { "positive": [ { "sentiment": "Popular", "topic": "games", "score": 0.6748984055823062, "original_text": "Popular games", "original_length": 13, "normalized_text": "Popular games", "normalized_length": 13, "offset": 0 }, { "sentiment": "engaging", "topic": "pop culture-inspired games", "score": 0.6280145725181376, "original_text": "engaging pop culture-inspired games", "original_length": 35, "normalized_text": "engaging pop culture-inspired games", "normalized_length": 35, "offset": 370 } ] } ] } $ require 'json' json = JSON.parse(json_string) puts json["sentiment_analysis"].first["positive"].first["score"] #=> 0.6748984055823062 
+1
source

It looks like the data is a JSON string. In this case, you can analyze it and do something like the following:

 require 'json' file = File.read('Code.org') data_hash = JSON.parse(file) score = data_hash['score'] 
+1
source

Source: https://habr.com/ru/post/1012850/


All Articles