【问题标题】:Unicode String support in java and pythonjava和python中的Unicode字符串支持
【发布时间】:2013-03-09 00:13:23
【问题描述】:

我有一个 Android 应用程序,我在其中读取短信并将其发送到谷歌应用引擎服务器。一些用户抱怨某些语言无法正常通过。

        // Execute query
        cursor = context.getContentResolver().query(
                SMS_PROVIDER_URI,
                SMS_QUERY_FIELDS,
                "date >= " + startDate.getTime(),  // selection - get messages > startDate
                null,                              // selectionArgs
                "date ASC");                       // order - get oldest messages first

        // Iterate results
        if (cursor != null && cursor.moveToFirst()) {

            // read through all the sms and create a list
            do {
                String sender              = cursor.getString(0);
                String message             = cursor.getString(2);
                boolean isIncomingMessage  = cursor.getString(3).contains("1");
                Date date                  = new Date(cursor.getLong(1));

                String contactName = ContactLookup.lookup(context, sender);

                smsList.add(new SMSMessageInfo(sender, contactName,
                        message, isIncomingMessage, date));

            } while (cursor.moveToNext());
        }

message 变量包含来自不同语言的短信。我如何支持它? 另外,我需要将它发送到我的服务器(python),如何翻译服务器上的 unicode?​​p>

【问题讨论】:

标签: java android python google-app-engine unicode


【解决方案1】:

在 Python 2.7 中有两类字符串,str(标准字符串,由字节组成)和unicode(由 unicode 字符组成,使用 u 前缀表示为文字:u"foo")。转换是通过使用实例上的方法完成的:

u"blä".encode('utf8') → "bl\xc3\xa4"  # from unicode to str
"bl\xc3\xa4".decode('utf8') → u"blä"  # from str to unicode

转换通常是隐式发生的,例如。 G。如果您将str 添加到unicode,则str 在连接之前会提升为unicode(默认情况下使用编码ascii)。

另一方面,获得printed 的unicode 实例将首先转换为str,使用取决于打印它的流的编码(通常也是ascii)。

这些自动转换的场合往往是异常的来源(即转换失败)。如果您捕获的异常过多,这些异常可能会被忽视,然后只是某些工具不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2013-05-28
    • 2011-08-15
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多