从Ruby中的文本文件中提取所选数据 [英] Extracting selected data from a text file in Ruby

查看:101
本文介绍了从Ruby中的文本文件中提取所选数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在研究从Ruby中的文本文件中提取信息. 那么如何从下面的文本文件中仅提取数字"0.6748984055823062"?

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.

推荐答案

下面是一个脚本,该脚本仅提取您想要的分数.

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

请记住两件事:

  • 您要查找的分数可能不是第一个
  • 数据是数组和哈希的组合


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

这篇关于从Ruby中的文本文件中提取所选数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆