Extracting selected data from a text file in Ruby

橙三吉。 提交于 2019-12-11 00:38:19

问题


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.


回答1:


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



回答2:


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']


来源:https://stackoverflow.com/questions/40936239/extracting-selected-data-from-a-text-file-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!