2017-10-08 235 views
0

我在python中使用了bing API進行拼寫糾正。儘管我得到了帶有建議的正確的Json格式,但它並未替換原始字符串。我試着用data.replace,但它不起作用。有沒有其他簡單的方法可以用建議的詞語替換原始字符串。如何用python bing替換單詞拼寫更正建議

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'}]} 

回答

0

你需要做自己更換你的文字。

您可以遍歷「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知識的情況下來到那裏,但你卻非常支持。「