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

2023-12-20

现在我正在用 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

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


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

要记住两件事:

  • 您要查找的分数可能不是第一个
  • 数据是数组和哈希的混合
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Ruby 中从文本文件中提取选定的数据 的相关文章

随机推荐