Language Detection
    • PDF

    Language Detection

    • PDF

    記事の要約

    Classic/VPC環境で利用できます。

    言語検出

    言語検出のユースケースを説明します。

    Java

    Javaベースの APIのサンプルコードは次の通りです。

    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    public class APIExamDetectLangs {
    
        public static void main(String[] args) {
            String clientId = "YOUR_CLIENT_ID";//アプリケーションクライアント ID値";
            String clientSecret = "YOUR_CLIENT_SECRET";//アプリケーションクライアントのシークレット値";
            try {
                String query = URLEncoder.encode("こんにちは。", "UTF-8");
                String apiURL = "https://naveropenapi.apigw.ntruss.com/langs/v1/dect";
                URL url = new URL(apiURL);
                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
                con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
                // post request
                String postParams = "query=" + query;
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(postParams);
                wr.flush();
                wr.close();
                int responseCode = con.getResponseCode();
                BufferedReader br;
                if(responseCode==200) { // 正常な呼び出し
                    br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                } else {  // エラー発生
                    br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                }
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = br.readLine()) != null) {
                    response.append(inputLine);
                }
                br.close();
                System.out.println(response.toString());
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    

    Python

    Pythonベースの APIのサンプルコードは次の通りです。

    import os
    import sys
    import urllib.request
    client_id = "YOUR_CLIENT_ID"
    client_secret = "YOUR_CLIENT_SECRET"
    encQuery = urllib.parse.quote("言語検出対象の文を入力してください")
    data = "query=" + encQuery
    url = "https://naveropenapi.apigw.ntruss.com/langs/v1/dect"
    request = urllib.request.Request(url)
    request.add_header("X-NCP-APIGW-API-KEY-ID",client_id)
    request.add_header("X-NCP-APIGW-API-KEY",client_secret)
    response = urllib.request.urlopen(request, data=data.encode("utf-8"))
    rescode = response.getcode()
    if(rescode==200):
        response_body = response.read()
        print(response_body.decode('utf-8'))
    else:
        print("Error Code:" + rescode)
    

    PHP

    PHPベースの APIのサンプルコードは次の通りです。

    <?php
      $client_id = "YOUR_CLIENT_ID";
      $client_secret = "YOUR_CLIENT_SECRET";
      $encQuery = urlencode("こんにちは。");
      $postvars = "query=".$encQuery;
      $url = "https://naveropenapi.apigw.ntruss.com/langs/v1/dect";
      $is_post = true;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, $is_post);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch,CURLOPT_POSTFIELDS, $postvars);
      $headers = array();
      $headers[] = "X-NCP-APIGW-API-KEY-ID: ".$client_id;
      $headers[] = "X-NCP-APIGW-API-KEY: ".$client_secret;
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      $response = curl_exec ($ch);
      $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      echo "status_code:".$status_code."<br />";
      curl_close ($ch);
      if($status_code == 200) {
        echo $response;
      } else {
        echo "エラー内容: ".$response;
      }
    ?>
    

    JavaScript

    JavaScriptベースの APIのサンプルコードは次の通りです。

    var express = require('express');
    var app = express();
    var client_id = 'YOUR_CLIENT_ID';
    var client_secret = 'YOUR_CLIENT_SECRET';
    var query = "言語検出対象の文を入力してください。";
    app.get('/detectLangs', function (req, res) {
       var api_url = 'https://naveropenapi.apigw.ntruss.com/langs/v1/dect';
       var request = require('request');
       var options = {
           url: api_url,
           form: {'query': query},
           headers: {'X-NCP-APIGW-API-KEY-ID':client_id, 'X-NCP-APIGW-API-KEY': client_secret}
        };
       request.post(options, function (error, response, body) {
         if (!error && response.statusCode == 200) {
           res.writeHead(200, {'Content-Type': 'text/json;charset=utf-8'});
           res.end(body);
         } else {
           res.status(response.statusCode).end();
           console.log('error = ' + response.statusCode);
         }
       });
     });
     app.listen(3000, function () {
       console.log('http://127.0.0.1:3000/detectLangs app listening on port 3000!');
     });
    

    C#

    C# ベースの APIのサンプルコードは次の通りです。

    using System;
    using System.Net;
    using System.Text;
    using System.IO;
    
    namespace NaverAPI_Guide
    {
        public class APIExamDetectLangs
        {
            static void Main(string[] args)
            {
                string url = "https://naveropenapi.apigw.ntruss.com/langs/v1/dect";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers.Add("X-NCP-APIGW-API-KEY-ID", "YOUR-CLIENT-ID");
                request.Headers.Add("X-NCP-APIGW-API-KEY", "YOUR-CLIENT-SECRET");
                request.Method = "POST";
                string query = "今日の天気はどうですか?";
                byte[] byteDataParams = Encoding.UTF8.GetBytes("query=" + query);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteDataParams.Length;
                Stream st = request.GetRequestStream();
                st.Write(byteDataParams, 0, byteDataParams.Length);
                st.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                string text = reader.ReadToEnd();
                stream.Close();
                response.Close();
                reader.Close();
                Console.WriteLine(text);
            }
        }
    }
    

    この記事は役に立ちましたか?

    What's Next
    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.