从Ruby中的文本文件中提取所选数据

时间:2016-12-02 15:58:20

标签: ruby text-files extract

现在我正在从Ruby中的文本文件中提取信息。 然后我怎样才能提取出数字' 0.6748984055823062'来自以下文本文件?

{
  "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
        },

我试过的是我可以读取一个文件并通过以下代码逐行打印。

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

我想将数字设置为变量,以便我可以处理它。

2 个答案:

答案 0 :(得分:2)

看起来数据是JSON字符串。在这种情况下,您可以解析它并执行以下操作:

require 'json'

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

score = data_hash['score']

答案 1 :(得分:2)

这是一个只提取你想要的分数的脚本。

要记住两件事:

  • 您正在寻找的分数可能不是第一个
  • 数据是数组和哈希的混合


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