COTOHA で固有名詞の抽出 (Golang)


COTOHA API Portal の使用例です。

フォルダー構造

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

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

// ---------------------------------------------------------------
func proper_noun_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/ne"
    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 := "特急はくたかで富山に向かいます。それから、金沢に行って、兼六園に行きます。"

    proper_noun_proc(config,sentence)

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

// ---------------------------------------------------------------

get_config.go get_token.go はこちら
COTOHA API で構文解析 (Golang)

実行コマンド

go run proper_noun.go get_config.go get_token.go

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

out01.json
{
  "result" : [ {
    "begin_pos" : 7,
    "end_pos" : 9,
    "form" : "富山",
    "std_form" : "富山",
    "class" : "LOC",
    "extended_class" : "",
    "source" : "basic"
  }, {
    "begin_pos" : 21,
    "end_pos" : 23,
    "form" : "金沢",
    "std_form" : "金沢",
    "class" : "LOC",
    "extended_class" : "",
    "source" : "basic"
  }, {
    "begin_pos" : 28,
    "end_pos" : 31,
    "form" : "兼六園",
    "std_form" : "兼六園",
    "class" : "LOC",
    "extended_class" : "",
    "source" : "basic"
  } ],
  "status" : 0,
  "message" : ""
}