Sookie J
Sookie J

Reputation: 893

Extracting 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 just 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 have tried is that I could read a file and print it line by line by 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 the number to a variable so that I can process it.

Upvotes: 2

Views: 1498

Answers (2)

Sara Fuerst
Sara Fuerst

Reputation: 6068

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

require 'json'

file = File.read('Code.org')
data_hash = JSON.parse(file)

score = data_hash['score']

Upvotes: 2

Eric Duminil
Eric Duminil

Reputation: 54223

Here's a script which extracts just the score you want.

Two things to keep in mind :

  • the score you're looking for might not be the first one
  • the data is a mix 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

Upvotes: 2

Related Questions