使用Microsoft Translator API获取多个翻译



我想根据API参考从Microsoft Translator API中使用/getTranslations方法来获得给定单词的多个Poosible翻译。不幸的是,GitHub上提供的示例已过时:过时的示例。我确实设法更新了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;
}

我以这种方式解决了问题:(包括emultiplipliplemtaltrestives桅杆是选项部分中的第一个)

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

Microsoft Translator的V2 API中的GetTranslations()和GetTranslationsArray()方法包括一个可选的布尔标志" Includemultipliplipliplipliplipliplipliplipliplytalnatives"。该方法将返回到MaxTranslations的替代方案,即使没有那么多可用的CTF条目,即从转换器引擎的N-最佳列表提供的Delta。返回机器生成的替代方案的等级为0。人类策划的替代方案的额定值为1或更高。

最新更新