首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Microsoft Translator API获取多个翻译

使用Microsoft Translator API获取多个翻译
EN

Stack Overflow用户
提问于 2017-03-07 20:48:01
回答 2查看 376关注 0票数 1

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

有没有人有一个有效的例子/知道我的代码的修复?

下面是我的代码:

代码语言:javascript
运行
复制
<?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;
}
EN

回答 2

Stack Overflow用户

发布于 2017-05-30 21:36:25

我这样解决了这个问题:(IncludeMultipleMTAlternatives必须是选项部分的第一个)

代码语言:javascript
运行
复制
<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>

票数 1
EN

Stack Overflow用户

发布于 2017-03-08 02:40:59

Microsoft Translator的V2应用程序接口中的GetTranslations()和GetTranslationsArray()方法包括一个可选的布尔标志"IncludeMultipleMTAlternatives“。即使没有那么多可用的maxTranslations条目,该方法也将返回到maxTranslations,其中增量是从翻译器引擎的n最佳列表中提供的。机器生成的备选方案返回评级为0。人工策划的替代方案的评级将为1或更高。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42648757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档