如何用python bing拼写纠正器建议替换单词

时间:2017-10-08 14:28:48

标签: python json spell-checking bing-api

我在python中使用了bing API进行拼写纠正。虽然我得到了正确的Json格式的建议,它不会取代原来的字符串。我尝试使用data.replace,但它不起作用。有没有其他简单的方法可以用建议的单词替换原始字符串。

import httplib,urllib,base64
headers = {
    # Request headers
    'Ocp-Apim-Subscription-Key': '7fdf55a1a7e42d0a7890bab142343f8'
}

params = urllib.urlencode({
    # Request parameters
    'text': 'Lectures were really good. There were lot of people who came their without any Java knowledge and yet you were very suppor.',
    'mode': 'proof',
    'preContextText': '{string}',
    'postContextText': '{string}',
    'mkt': '{string}',
})

try:
    conn = httplib.HTTPSConnection('api.cognitive.microsoft.com')
    conn.request("GET", "/bing/v5.0/spellcheck/?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

输出(漂亮印刷):

{'_type': 'SpellCheck',
 'flaggedTokens': [{'offset': 61,
                    'suggestions': [{'score': 0.854956767552189,
                                     'suggestion': 'there'}],
                    'token': 'their',
                    'type': 'UnknownToken'},
                   {'offset': 116,
                    'suggestions': [{'score': 0.871971469417366,
                                     'suggestion': 'support'}],
                    'token': 'suppor',
                    'type': 'UnknownToken'}]}

1 个答案:

答案 0 :(得分:1)

您需要自己在文本中进行替换。

您可以迭代' flaggedTokens',获取每个令牌的偏移量,找到最佳建议并根据建议替换令牌:

import operator


text = 'Lectures were really good. There were lot of people who came their without any Java knowledge and yet you were very suppor.'

data = {'_type': 'SpellCheck',
        'flaggedTokens': [{'offset': 61,
                'suggestions': [{'score': 0.854956767552189,
                                 'suggestion': 'there'}],
                'token': 'their',
                'type': 'UnknownToken'},
               {'offset': 116,
                'suggestions': [{'score': 0.871971469417366,
                                 'suggestion': 'support'}],
                'token': 'suppor',
                'type': 'UnknownToken'}]}

shifting = 0
correct = text
for ft in data['flaggedTokens']:
    offset = ft['offset']
    suggestions = ft['suggestions']
    token = ft['token']

    # find the best suggestion
    suggestions.sort(key=operator.itemgetter('score'), reverse=True)
    substitute = suggestions[0]['suggestion']

    # replace the token by the suggestion
    before = correct[:offset + shifting]
    after = correct[offset + shifting + len(token):]
    correct = before + substitute + after
    shifting += len(substitute) - len(token)

print(correct)

你得到:“讲座真的很棒。有很多人在没有任何Java知识的情况下来到那里,但你们非常支持。“