【问题标题】:Extracting selected data from a text file in Ruby从 Ruby 中的文本文件中提取选定的数据
【发布时间】:2016-12-03 05:13:27
【问题描述】:

现在我正致力于从 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 文件的一部分。你试过JSON.parse吗?
  • 哦,你可能是对的。文件格式看起来像 JSON。我会尝试 JSON.parse。
  • 请阅读“minimal reproducible example”。询问时,代码和数据允许测试是很重要的。 JSON 示例在语法上不正确,迫使我们修复它只是为了帮助您。这会浪费我们的时间,所以请帮助我们。

标签: ruby text-files extract


【解决方案1】:

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

要记住两件事:

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


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】:

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

    require 'json'
    
    file = File.read('Code.org')
    data_hash = JSON.parse(file)
    
    score = data_hash['score']
    

    【讨论】:

    • 你能再看一下文件吗?文本是嵌套的,所以看起来我无法使用您建议的代码。
    • 您要求的号码没有出现在您提供的示例中,但应该可以导航到它或使用[]遍历所有可能的匹配项。
    • Ruby 不对字符串文字使用反引号。单引号或双引号都是可接受的,并将用作require 语句的参数。反引号用于在子 shell 中执行命令并返回 STDOUT。此外,data_hash['score'] 不会返回 OP 想要的内容,而是返回“nil”。我建议您尝试运行您的代码。
    • @theTinMan 是的,这完全是我的错误输入。感谢您修复它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2011-04-20
    相关资源
    最近更新 更多