LoginSignup
1
0

More than 3 years have passed since last update.

COTOHA API で構文解析 (Golang)

Posted at

COTOHA API Portal の使用例です。

フォルダー構造

$ tree -a
.
├── .env
├── get_config.go
├── get_token.go
└── parsing.go
// ---------------------------------------------------------------
//
//  parsing.go
//
//                  Feb/25/2020
// ---------------------------------------------------------------
package main

import (
    "fmt"
    "os"
    "encoding/json"
    "net/http"
    "strings"
    "io/ioutil"
)

// ---------------------------------------------------------------
func parse_proc(config map[string]interface{},sentence string) {
    out_filename := "out01.json"
    fmt.Printf("%s\n",sentence)

    data := make (map[string]interface{})
    data["sentence"] = sentence
    data["type"] = "default"
    str_json, _ := json.Marshal(data)
    fmt.Printf("%s\n",str_json)

    url_base := config["url_base"]
    fmt.Printf("%s\n",url_base)
    url_target := url_base.(string) + "v1/parse"
    fmt.Printf("%s\n",url_target)

    req, _ := http.NewRequest("POST", url_target, strings.NewReader(string(str_json)))

    req.Header.Set("Content-Type","application/json") 
    req.Header.Set("Authorization", "Bearer " + config["access_token"].(string))

    client := new(http.Client)
    resp, error := client.Do(req)
    if error != nil {
        fmt.Println("*** error *** client.Do ***")
        fmt.Println("Request error:", error)
        }

    bb, err := ioutil.ReadAll(resp.Body)
    if err == nil {
        ioutil.WriteFile (out_filename,bb,0666)

        var unit_aa map[string]interface{}
        json.Unmarshal ([]byte(string(bb)), &unit_aa)
        fmt.Printf("len(unit_aa) = %d\n", len(unit_aa))
        unit_bb := unit_aa["result"]
        fmt.Println(unit_bb)
        }   


}

// ---------------------------------------------------------------
func main() {

    fmt.Fprintf (os.Stderr,"*** 開始 ***\n")

    config := get_config_proc ()

    access_token := get_token_proc (config)

    config["access_token"] = access_token

    fmt.Printf("%s\n",config["access_token"])

    sentence := "特急はくたか"

    parse_proc(config,sentence)

    fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}

// ---------------------------------------------------------------
get_config.go
// ---------------------------------------------------------------
//
//  get_config.go
//
//                  Feb/25/2020
// ---------------------------------------------------------------
package main

import (
    "fmt"
    "os"
    "github.com/joho/godotenv"
)

// ---------------------------------------------------------------
func get_config_proc () map[string]interface{} {
    err := godotenv.Load()
    if err != nil {
        fmt.Println("Error loading .env file")
        }

    config := make (map[string]interface{})
    config["grantType"] = "client_credentials"
    config["clientId"] = os.Getenv("CLIENT_ID")
    config["clientSecret"] = os.Getenv("CLIENT_SECRET")
    config["url_base"] = os.Getenv("DEVELOPER_API_BASE_URL")
    config["url_target"] = os.Getenv("ACCESS_TOKEN_PUBLISH_URL")

    return (config)
}

// ---------------------------------------------------------------
get_token.go
// ---------------------------------------------------------------
//
//  get_token.go
//
//                  Feb/25/2020
// ---------------------------------------------------------------
package main

import (
    "fmt"
    "strings"
    "io/ioutil"
    "net/http"
    "encoding/json"
)

// ---------------------------------------------------------------
func get_token_proc (config map[string]interface{}) string {
    access_token := ""
    str_json, _ := json.Marshal(config)

    url_target := config["url_target"].(string)
    response, error := http.Post(url_target,"application/json",
        strings.NewReader(string(str_json)))
    if error != nil {
        fmt.Println("Request error:", error)
    }

    bb, err := ioutil.ReadAll(response.Body)
    if err == nil {
//      fmt.Println(string(bb))

        var unit_aa map[string]interface{}
        json.Unmarshal ([]byte(string(bb)), &unit_aa)
        access_token = unit_aa["access_token"].(string)
        }

    return (access_token)
}
// ---------------------------------------------------------------

実行コマンド

go run parsing.go get_config.go get_token.go

次のJSONファイルが作成されます。

out01.json
{
  "result" : [ {
    "chunk_info" : {
      "id" : 0,
      "head" : 1,
      "dep" : "D",
      "chunk_head" : 1,
      "chunk_func" : 2,
      "links" : [ ]
    },
    "tokens" : [ {
      "id" : 0,
      "form" : "特急",
      "kana" : "トッキュウ",
      "lemma" : "特急",
      "pos" : "名詞",
      "features" : [ "形容" ],
      "attributes" : { }
    }, {
      "id" : 1,
      "form" : "は",
      "kana" : "ハ",
      "lemma" : "はく",
      "pos" : "動詞語幹",
      "features" : [ "K" ],
      "dependency_labels" : [ {
        "token_id" : 0,
        "label" : "nmod"
      }, {
        "token_id" : 2,
        "label" : "aux"
      } ],
      "attributes" : { }
    }, {
      "id" : 2,
      "form" : "く",
      "kana" : "ク",
      "lemma" : "く",
      "pos" : "動詞接尾辞",
      "features" : [ "連体" ],
      "attributes" : { }
    } ]
  }, {
    "chunk_info" : {
      "id" : 1,
      "head" : -1,
      "dep" : "O",
      "chunk_head" : 0,
      "chunk_func" : 0,
      "links" : [ {
        "link" : 0,
        "label" : "adjectivals"
      } ]
    },
    "tokens" : [ {
      "id" : 3,
      "form" : "たか",
      "kana" : "タカ",
      "lemma" : "鷹",
      "pos" : "名詞",
      "features" : [ ],
      "dependency_labels" : [ {
        "token_id" : 1,
        "label" : "amod"
      } ],
      "attributes" : { }
    } ]
  } ],
  "status" : 0,
  "message" : ""
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0