由于UnicodeEncodeError,未能调用印地文语音API

时间:2019-01-08 19:50:13

标签: encoding python-requests ascii hindi

我正在尝试调用一个API,该API将印地文文本转换为语音,但是每当我调用此API时:

http://ivrapi.indiantts.co.in/tts?type=indiantts&text='+response+'&api_key=xyx&user_id=abc&action=play&numeric=hcurrency&lang=hi_mohita

其中response=any text in hindi

错误:

playwav(urlopen('http://ivrapi.indiantts.co.in/tts?type=indiantts&text='+response+'&api_key=xyz&user_id=abc&action=play&numeric=hcurrency&lang=hi_mohita'))

  File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.5/urllib/request.py", line 466, in open
    response = self._open(req, data)
  File "/usr/lib/python3.5/urllib/request.py", line 484, in _open
    '_open', req)
  File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.5/urllib/request.py", line 1282, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/usr/lib/python3.5/urllib/request.py", line 1254, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "/usr/lib/python3.5/http/client.py", line 1107, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1142, in _send_request
    self.putrequest(method, url, **skips)
  File "/usr/lib/python3.5/http/client.py", line 984, in putrequest
    self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 29-31: ordinal not in range(128)

我尝试将编码和解码转换为utf8和unicode()函数,但没有任何效果。

1 个答案:

答案 0 :(得分:1)

这有效

response="मैं आपको बता दूंगा"
print(response)
params = {'text':response.encode('UTF-8'), 'api_key': 'abc','user_id':'xyz','action':'play','numeric':'hcurrency','lang':'hi_mohita'}
print('http://ivrapi.indiantts.co.in/tts?type=indiantts&'+urllib.parse.urlencode(params))
playwav(urlopen('http://ivrapi.indiantts.co.in/tts?type=indiantts&'+urllib.parse.urlencode(params)))