gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:55 24 4
gpt4 key购买 nike

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

关于ruby - 从 Ruby 中的文本文件中提取选定的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com