2017-10-08 29 views
0

파이썬에서 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'을 반복 할 수있는 각 토큰의 오프셋 (offset) 얻을, 최고의 제안을 찾아 제안에 의해 토큰을 대체 :

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에 대한 지식 없이도 많은 사람들이 방문했지만 많은 도움을 받았습니다. "