2016-12-02 8 views
2

Rubyでテキストファイルから情報を抽出する作業を進めています。 次に、「0.6748984055823062」という数字だけを次のテキストファイルから抽出するにはどうすればよいですか?Rubyでテキストファイルから選択したデータを抽出する

{ 
    "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 

数値を変数に設定して処理できるようにしたいとします。

+0

ファイルを読み込んで1行ずつ印刷する方法を知りました。しかし、抽出は難しいです。 –

+3

これはJSONファイルの一部のようです。 ['JSON.parse'](https://ruby-doc.org/stdlib-2.3.1/libdoc/json/rdoc/JSON.html#module-JSON-label-Parsing+JSON)を試しましたか? –

+0

ああ、そうかもしれない。ファイル形式はJSONのようです。私はJSON.parseを試みます。 –

答えて

1

ここでは、必要なスコアだけを抽出するスクリプトです。心に留めておくべき

2つのこと:

  • あなたが探しているスコアは、データが配列の組み合わせである第一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 
1

データがJSON文字列のようです。その場合、それを解析して次のようなことをすることができます:

require 'json' 

file = File.read('Code.org') 
data_hash = JSON.parse(file) 

score = data_hash['score'] 
+1

ファイルをもう一度見てみましょうか?テキストはネストされているので、あなたが提案したコードを使用することはできません。 –

+0

あなたが提示している番号は、あなたが表示しているサンプルには表示されませんが、 '[]'を使ってすべての可能なマッチに対してナビゲートしたり、繰り返すことができます。 – tadman

+1

Rubyは文字列リテラルにバッククォートを使用しません。一重引用符または二重引用符は受け入れられ、 'require'ステートメントのパラメータとして使用されます。バック・チックは、サブ・シェル内でコマンドを実行し、STDOUTを戻すために使用されます。また、 'data_hash ['score']'はOPが望むものを返さず、代わりに 'nil'を返します。あなたのコードを実行してみることをお勧めします。 –

関連する問題