python - UnicodeEncodeError: 'ascii' codec can't encode character '\u030c' in position 142: ordinal not in range(128) -
import json import codecs urllib.request import urlopen url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myapikeyhere&lang=hr-en&text=" word_list = codecs.open("inputfile.txt", encoding='utf-8').read().split(" ") recnik = codecs.open('translation.txt', encoding='utf-8', mode='w') search_term in word_list: response = urlopen(url+search_term) translation = json.loads(response.readall().decode('utf-8')) translation = translation['text'][0] one_string = search_term + " " + translation + '\n' recnik.write(one_string)
i'm trying translate few words have in text file using yandex.ru's api. after first few words translated following error:
unicodeencodeerror: 'ascii' codec can't encode character '\u030c' in position 142: ordinal not in range(128)
it happens when encounters first word in wordlist non ascii character. far know i'm doing in unicode, missing obvious , appreciate else's eyes on this.
error occurs on line:
response = urlopen(url+search_term)
edit:
the solution used in case can in future:
import json import codecs urllib.request import urlopen urllib.parse import quote url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myapikey=hr-en&text=" word_list = codecs.open("inputfile.txt", encoding='utf-8').read().split(" ") recnik = codecs.open('translation.txt', encoding='utf-8', mode='w') search_term in word_list: send = url+quote(search_term) response = urlopen(send) translation = json.loads(response.readall().decode('utf-8')) translation = translation['text'][0] one_string = search_term + " " + translation print(one_string) one_string += '\n' recnik.write(one_string)
Comments
Post a Comment