Python Papago translation result utf - Return to string after 8 decode

Asked 2 years ago, Updated 2 years ago, 100 views

import os
import sys
import urllib.request
text = "text sample."
encQuery = urllib.parse.quote(text)
data = "query=" + encQuery
url = "https://openapi.naver.com/v1/papago/detectLangs"
request = urllib.request.Request(url)
request.add_header("X-Naver-Client-Id",client_id)
request.add_header("X-Naver-Client-Secret",client_secret)
response = urllib.request.urlopen(request, data=data.encode("utf-8"))
rescode = response.getcode()
if(rescode==200):
    response_body = response.read()
    a = response_body.decode('utf-8')
    print(a)

else:
    print("Error Code:" + rescode)

I'm going to use the Naver Papago language automatic recognition API.

After entering the desired text, I printed the translated character with a.

After decoding with decode('utf-8'), the result is {"langCode":"en"} Appears as

The type is str, but you can't slice it.

if a is '"langCode":"en"':

If it is 'en', I want to make another code, but I don't think I can recognize it.

What's the problem?ㅠ<

Thank you.

python-3.x

2022-09-21 11:18

1 Answers

import json
#... an intermediate omission
if(rescode==200):
    response_body = response.read()
    a = response_body.decode('utf-8')
    b = json.loads(a)
    if b['langCode'] == 'en':
        print ('RESULT : SUCCESS')
#... The following is omitted

RESULT : SUCCESS

Try converting Json data into dictionaries.


2022-09-21 11:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.