programing

루비의 JSON 파일에서 구문 분석 및 중첩된 해시에서 숫자 추출

jooyons 2023. 3. 1. 10:42
반응형

루비의 JSON 파일에서 구문 분석 및 중첩된 해시에서 숫자 추출

저는 지금 루비의 JSON 파일에서 정보를 추출하는 작업을 하고 있습니다.그럼 어떻게 하면 다음 텍스트 파일에서 '점수' 옆에 있는 숫자만 추출할 수 있을까요?예를 들어 0.6748984055823062, 0.6280145725181376을 켜고 켜겠습니다.

{
  "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
        },
     "negative": [
    {
      "sentiment": "get sucked into",
      "topic": "the idea of planning",
      "score": -0.7923352042939829,
      "original_text": "Students get sucked into the idea of planning",
      "original_length": 45,
      "normalized_text": "Students get sucked into the idea of planning",
      "normalized_length": 45,
      "offset": 342
    },
    {
      "sentiment": "be daunted",
      "topic": null,
      "score": -0.5734506634410159,
      "original_text": "initially be daunted",
      "original_length": 20,
      "normalized_text": "initially be daunted",
      "normalized_length": 20,
      "offset": 2104
    },

JSON 메서드를 사용하여 파일을 읽고 텍스트 파일을 해시 변수로 설정할 수 있습니다.

require 'json'
json = JSON.parse(json_string)

사용방법JSON클래스:

파일 가져오기:

require "json"
file = File.open "/path/to/your/file.json"
data = JSON.load file

옵션으로 지금 닫을 수 있습니다.

file.close

파일은 다음과 같습니다.

{
  "title": "Facebook",
  "url": "https://www.facebook.com",
  "posts": [
    "lemon-car",
    "dead-memes"
  ]
}

이제 파일을 다음과 같이 읽을 수 있습니다.

data["title"]
=> "Facebook"
data.keys
=> ["title", "url", "posts"]
data['posts']
=> ["lemon-car", "dead-memes"]
data["url"]
=> "https://www.facebook.com"

도움이 됐으면 좋겠네요!

파일에서 데이터 구문 분석:

data_hash = JSON.parse(File.read('file-name-to-be-read.json'))

그럼 그냥 데이터를 지도화해!

reviews = data_hash['sentiment_analysis'].first
reviews.map do |sentiment, reviews|
  puts "#{sentiment} #{reviews.map { |review| review['score'] }}"
end

이게 가장 간단한 답인 것 같아요.

사용할 수 있습니다.Array#map리뷰를 수집합니다.

reviews = json['sentiment_analysis'][0]
positive_reviews = reviews['positive']
negative_reviews = reviews['negative']

positive_reviews.map { |review| review['score'] }
=> [0.6748984055823062, 0.6280145725181376]

negative_reviews.map { |review| review['score'] }
=> [-0.7923352042939829, -0.5734506634410159]

이게 도움이 됐으면 좋겠네요!

언급URL : https://stackoverflow.com/questions/40942569/parsing-from-a-json-file-in-ruby-and-extract-numbers-from-nested-hashes

반응형