使用Bing Spell Check API v7解决重音和编码问题

问题描述 投票:1回答:1

因此,我正在尝试使用PHP中的Bing的拼写检查API,但我遇到的问题是,重音和其他特殊字符未正确解码,会产生许多错误,这些错误不在原始文本中并且会弄乱偏移量。

我的实现非常简单 - 它主要基于他们在文档中提供的示例。我不确定我是不是应该做一些不同的事情,或者如果他们如何解码这些特殊字符(这似乎非常不可能 - 我搞乱了一些事情更可能......),这是一个问题。

这是代码:

$host = 'https://api.cognitive.microsoft.com';
$path = '/bing/v7.0/spellcheck?';

$data = array (
    'mkt' => $lang,
    'mode' => 'proof',
    'text' => urlencode($text)
);

$encodedData = http_build_query($data);
$key = 'subscription key redacted for obvious reasons';

$headers =  "Content-type: application/x-www-form-urlencoded\r\n" .
            "Ocp-Apim-Subscription-Key: $key\r\n";

if (isset($_SERVER['REMOTE_ADDR']))
    $headers .= "X-MSEdge-ClientIP: " . $_SERVER['REMOTE_ADDR'] . "\r\n";

$options = array (
    'http' => array (
        'header' => $headers,
        'method' => 'POST',
        'content' => $encodedData
    )
);
$context  = stream_context_create ($options);
$result = file_get_contents ($host . $path, false, $context);

if ($result === FALSE) {
    # Handle error
}

$decodedResult = json_decode($result, true);

例如,如果我尝试拼写检查以下字符串:

D'机构

$ encodedData成为以下内容:

mkt=fr-CA&method=proof&text=d%25E2%2580%2599institutions

我从API获得的结果如下:

array(2) {
  ["_type"]=>
  string(10) "SpellCheck"
  ["flaggedTokens"]=>
  array(1) {
    [0]=>
    array(4) {
      ["offset"]=>
      int(8)
      ["token"]=>
      string(14) "99institutions"
      ["type"]=>
      string(12) "UnknownToken"
      ["suggestions"]=>
      array(2) {
        [0]=>
        array(2) {
          ["suggestion"]=>
          string(15) "99 institutions"
          ["score"]=>
          float(0.93191315174102)
        }
        [1]=>
        array(2) {
          ["suggestion"]=>
          string(14) "99 institution"
          ["score"]=>
          float(0.6518044080768)
        }
      }
    }
  }
}

正如您所看到的,解码似乎有问题,因为%被编码两次,并且只有一次被解码。现在,如果我在$ data中设置'text'的值时删除了url_encode(),它对于撇号可以正常工作,但它不适用于重音符号。例如,以下字符串:

责任

被API解释为

责任©

返回错误。

这很可能是我忽略的一些简单的事情,但我已经在这方面苦苦挣扎了很长一段时间并且会感谢我能得到的任何帮助。

谢谢,

- 埃米尔

[编辑]嗯,一如既往......如果有疑问,假设你错了。 API建议更改常规字母的所有重音,因为即使指定的语言是法语,它仍然提供英语建议而不是返回空数组。至于那些似乎没有被解码的口音,那么......我在没有任何doctype设置的情况下对这些数据进行了var_dump,因此当然没有正确的编码就会显示出来。很抱歉 - 最后,只需删除urlencode()即可!

php microsoft-cognitive bing-api
1个回答
1
投票

根据docs

API支持两种校对模式,Proof和Spell。默认模式是Proof。 Proof拼写模式提供最全面的检查,但仅在en-US(英国 - 美国)市场上可用。对于所有其他市场,请将模式查询参数设置为“拼写”。拼写模式可以找到大多数拼写错误,但没有找到Proof捕获的一些语法错误(例如,大写和重复的单词)。

© www.soinside.com 2019 - 2024. All rights reserved.