使用Microsoft Translator API获取多个翻译

时间:2017-03-07 12:48:01

标签: php microsoft-cognitive

我想根据API reference使用Microsoft Translator API中的/ getTranslations方法为给定单词获取多个poosible翻译。不幸的是,github上提供的示例已过时:Outdated Example。我确实设法更新了getTokens函数并引用了它,我确实得到了一个翻译,但我需要多个。

有没有人有一个工作示例/知道我的代码修复?

这是我的代码:

<?php
class AccessTokenAuthentication {
    /*
     * Get the access token.
     *
     * @param string $grantType    Grant type.
     * @param string $scopeUrl     Application Scope URL.
     * @param string $clientID     Application client ID.
     * @param string $clientSecret Application client ID.
     * @param string $authUrl      Oauth Url.
     *
     * @return string.
     */
function getToken($azure_key)
{
    $url = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken';
    $ch = curl_init();
    $data_string = json_encode('{body}');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string),
            'Ocp-Apim-Subscription-Key: ' . $azure_key
        )
    );
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $strResponse = curl_exec($ch);
    curl_close($ch);
    return $strResponse;
}
}
/*
 * Class:HTTPTranslator
 *
 * Processing the translator request.
 */
Class HTTPTranslator {
    /*
     * Create and execute the HTTP CURL request.
     *
     * @param string $url        HTTP Url.
     * @param string $authHeader Authorization Header string.
     *
     * @return string.
     *
     */
    function curlRequest($url, $authHeader) {
        //Initialize the Curl Session.
        $ch = curl_init();
        //Set the Curl url.
        curl_setopt ($ch, CURLOPT_URL, $url);
        //Set the HTTP HEADER Fields.
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml", 'Content-Length: 0'));
        //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
        //Set HTTP POST Request.
        curl_setopt($ch, CURLOPT_POST, TRUE);
        //Execute the  cURL session.
        $curlResponse = curl_exec($ch);
        //Get the Error Code returned by Curl.
        $curlErrno = curl_errno($ch);
        if ($curlErrno) {
            $curlError = curl_error($ch);
            throw new Exception($curlError);
        }
        //Close a cURL session.
        curl_close($ch);
        return $curlResponse;
    }
}
try {
    //Azure Key
    $azure_key      = "<my key>";
    //Client ID of the application.
    //$clientID       = "clientId";
    //Client Secret key of the application.
    //$clientSecret = "ClientSecret";
    //OAuth Url.
    $authUrl      = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
    //Application Scope Url
    //$scopeUrl     = "http://api.microsofttranslator.com";
    //Application grant type
    //$grantType    = "client_credentials";
    //Create the AccessTokenAuthentication object.
    $authObj      = new AccessTokenAuthentication();
    //Get the Access token.
    $accessToken  = $authObj->getToken($azure_key);
    //Create the authorization Header string.
    $authHeader = "Authorization: Bearer ". $accessToken;
    //Set the Params.
    $inputStr        = "get";
    $fromLanguage   = "en";
    $toLanguage        = "de";
    //$user            = 'TestUser';
    $category       = "general";
    //$uri             = null;
    $contentType    = "text/plain";
    $maxTranslation = 5;
    //Create the string for passing the values through GET method.
    $params = "from=$fromLanguage".
                "&to=$toLanguage".
                "&maxTranslations=$maxTranslation".
                "&text=".urlencode($inputStr).
                //"&user=$user".
                //"&uri=$uri".
                "&contentType=$contentType";
    //HTTP getTranslationsMethod URL.
    $getTranslationUrl = "http://api.microsofttranslator.com/V2/Http.svc/GetTranslations?$params";
    //Create the Translator Object.
    $translatorObj = new HTTPTranslator();
    //Call the curlRequest.
    $curlResponse = $translatorObj->curlRequest($getTranslationUrl, $authHeader);
    //Interprets a string of XML into an object.
    $xmlObj = simplexml_load_string($curlResponse);
    $translationObj = $xmlObj->Translations;
    $translationMatchArr = $translationObj->TranslationMatch;
    print_r($translationMatchArr);
    echo "Get Translation For <b>$inputStr</b>";
    echo "<table border ='2px'>";
    echo "<tr><td><b>Count</b></td><td><b>MatchDegree</b></td>
        <td><b>Rating</b></td><td><b>TranslatedText</b></td></tr>";
    foreach($translationMatchArr as $translationMatch) {
        echo "<tr><td>$translationMatch->Count</td><td>$translationMatch->MatchDegree</td><td>$translationMatch->Rating</td>
            <td>$translationMatch->TranslatedText</td></tr>";
    }
    echo "</table></br>";
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage() . PHP_EOL;
}

2 个答案:

答案 0 :(得分:1)

我用这种方式解决了这个问题: (IncludeMultipleMTAlternatives mast在选项部分中排在第一位)

&#13;
&#13;
<GetTranslationsArrayRequest>
  <AppId></AppId>
  <From>en</From>
  <Options>
    <IncludeMultipleMTAlternatives xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">true</IncludeMultipleMTAlternatives>
    <State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">777</State>
  </Options>
  <Texts>
  	<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">world</string>
  	<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">sun</string>
  </Texts>
  <To>ru</To>
  <MaxTranslations>10</MaxTranslations>
</GetTranslationsArrayRequest>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Microsoft Translator的V2 API中的GetTranslations()和GetTranslationsArray()方法包括可选的布尔标志“IncludeMultipleMTAlternatives”。 即使没有尽可能多的CTF条目,该方法也将返回maxTranslations替代方案,其中delta是从翻译器引擎的n-best列表提供的。返回的机器生成的替代品的评级为0.人工策划的替代品的评级为1或更高。