Python socket.send编码

时间:2013-07-04 23:25:58

标签: python sockets encoding

我似乎遇到了编码本身的问题,我需要传递Bing翻译容器..

def _unicode_urlencode(params):
    if isinstance(params, dict):
        params = params.items()
    return urllib.urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params])

def _run_query(args):
        data = _unicode_urlencode(args)
        sock = urllib.urlopen(api_url + '?' + data)
        result = sock.read()
        if result.startswith(codecs.BOM_UTF8):
                result = result.lstrip(codecs.BOM_UTF8).decode('utf-8')
        elif result.startswith(codecs.BOM_UTF16_LE):
                result = result.lstrip(codecs.BOM_UTF16_LE).decode('utf-16-le')
        elif result.startswith(codecs.BOM_UTF16_BE):
                result = result.lstrip(codecs.BOM_UTF16_BE).decode('utf-16-be')
        return json.loads(result)

def set_app_id(new_app_id):
        global app_id
        app_id = new_app_id

def translate(text, source, target, html=False):
        """
        action=opensearch
        """
        if not app_id:
                raise ValueError("AppId needs to be set by set_app_id")
        query_args = {
                'appId': app_id,
                'text': text,
                'from': source,
                'to': target,
                'contentType': 'text/plain' if not html else 'text/html',
                'category': 'general'
        }
        return _run_query(query_args)
...
text = translate(sys.argv[2], 'en', 'tr')
HOST = '127.0.0.1'
PORT = 894
s = socket.socket()
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.connect((HOST, PORT))
s.send("Bing translation: " + text.encode('utf8') + "\r");
s.close()

如您所见,如果翻译的文本包含一些土耳其语字符,则脚本无法将文本发送到套接字..

你对如何摆脱这个有任何想法吗?

问候。

2 个答案:

答案 0 :(得分:2)

您的问题与套接字完全无关。 text已经是一个字节字符串,您正在尝试对其进行编码。会发生什么是Python尝试通过安全的ASCII编码将bytestring转换为unicode,以便能够编码为UTF-8,然后失败,因为bytestring包含非ASCII字符。

您应该使用返回unicode对象的JSON变量来修复translate以返回unicode对象。

或者,如果它已编码为UTF-8编码的文本,则只需使用

即可
s.send("Bing translation: " + text + "\r")

答案 1 :(得分:-1)

# -*- coding:utf-8 -*-

 text = u"text in you language"
 s.send(u"Bing translation: " + text.encode('utf8') + u"\r");

这必须奏效。 text必须拼写为utf-8编码。