2013-03-09 47 views
0

我有一个Android应用程序,我在那里读取短信并将其发送到谷歌应用程序引擎服务器。一些用户抱怨说某些语言没有正确通过。在java和python中支持Unicode字符串

 // 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()); 
     } 

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

+0

Python与Unicode的效果很好。这是一篇综合性文章:http://docs.python.org/2/howto/unicode.html – jyore 2013-03-09 00:41:33

回答

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添加到unicodestr将在拼接之前被提升为unicode(默认情况下使用编码ascii)。

在另一方面,一个unicode实例得到print编将使用依赖于它被印上(通常ascii以及)的流的编码转换为一个str第一,。

这些自动转换的场合往往是异常的来源(即如果转换失败)。如果你发现太多例外,这些可能会被忽视,然后只是一些设施不起作用。