Court Info Extraction Project

1. Php Unicode escape to utf8 byte
function unescape($str) {
    $str = rawurldecode($str);
    preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
    $ar = $r[0];
    //print_r($ar);
    foreach($ar as $k=>$v) {
        if(substr($v,0,2) == "%u"){
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("H4",substr($v,-4)));
  }
        elseif(substr($v,0,3) == "&#x"){
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("H4",substr($v,3,-1)));
  }
        elseif(substr($v,0,2) == "&#") {
            
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("n",substr($v,2,-1)));
        }
    }
    return join("",$ar);
}
echo unescape("紫星蓝");
今天有用户反馈,表单系统用户提交的数据中文会乱码。测试发现问题出在 iconv 转换上。
iconv('UCS-2', 'GBK', '中文')
Google 搜索发现,原因是 Linux 服务器上 UCS-2 编码方式与 Winodws 不一致。
于是,我改成  iconv('UCS-2BE', 'GBK', '中文') 试试,中文正常了
 
以下是有关两个平台 UCS-2 编码的潜规则:


1, UCS-2 不等于 UTF-16。 UTF-16 每个字节使用 ASCII 字符范围编码,而 UCS-2 对每个字节的编码可以超出 ASCII 字符范围。UCS-2 和 UTF-16 对每个字符至多占两个字节,但是他们的编码是不一样的。


2, 对于 UCS-2, windows 下默认是 UCS-2LE。用 MultibyteToWidechar(或者A2W)生成的是 UCS-2LE 的 unicode。windows记事本可以将文本保存为 UCS-2BE,相当于多了层转换。


3, 对于 UCS-2, linux 下默认是 UCS-2BE。用iconv(指定UCS-2)来转换生成的是 UCS-2BE 的 unicode。如果转换windows平台过来的 UCS-2, 需要指定 UCS-2LE。


4, 鉴于windows和linux等多个平台对 UCS-2 的理解不同(UCS-2LE,UCS-2BE)。MS 主张 unicode 有个引导标志(UCS-2LE FFFE, UCS-2BE FEFF),以表明下面的字符是 unicode 并且判别 big-endian 或 little-endian。 所以从 windows 平台过来的数据发现有这个前缀,不用慌张。


5, linux 的编码输出,比如从文件输出,从 printf 输出,需要控制台做适当的编码匹配(如果编码不匹配,一般和该程序编译时的编码有若干关系),而控制台的转换输入需要查看当前的系统编码。比如控制台当前的编码是 UTF-8, 那么 UTF-8 编码的东西能正确显示,GBK 就不能;同样,当前编码是 GBK, 就能显示 GBK 编码,后来的系统应该更智能的处理好更多的转换了。不过通过 putty 等终端还是需要设置好终端的编码转换以解除乱码的烦恼。
PHP中对汉字进行UNICODE编码和解码的实现
 //将内容进行UNICODE编码
function unicode_encode($name)
{
    $name = iconv('UTF-8', 'UCS-2', $name);
    $len = strlen($name);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2)
    {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0)
        {    // 两个字节的文字
            $str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
        }
        else
        {
            $str .= $c2;
        }
    }
    return $str;
}
$name = 'MY,你大爷的';
$unicode_name=unicode_encode($name);
echo '<h3>'.$unicode_name.'</h3>';
// 将UNICODE编码后的内容进行解码
function unicode_decode($name)
{
    // 转换编码,将Unicode编码转换成可以浏览的utf-8编码
    $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
    preg_match_all($pattern, $name, $matches);
    if (!empty($matches))
    {
        $name = '';
        for ($j = 0; $j < count($matches[0]); $j++)
        {
            $str = $matches[0][$j];
            if (strpos($str, '\\u') === 0)
            {
                $code = base_convert(substr($str, 2, 2), 16, 10);
                $code2 = base_convert(substr($str, 4), 16, 10);
                $c = chr($code).chr($code2);
                $c = iconv('UCS-2', 'UTF-8', $c);
                $name .= $c;
            }
            else
            {
                $name .= $str;
            }
        }
    }
    return $name;
}
echo 'MY,\u4f60\u5927\u7237\u7684 -> '.unicode_decode($unicode_name);


2. python2.7 json dump unicode problem
Given an object containing py27 unicode string, json.dumps default method will convert all unicode string into unicode escape characters. Under the same situation, when ensure_ascii=False argument is explicitly provided, a unicode encode error will be raised: "UnicodeEncodeError: 'ascii' codec can't encode characters in position 15-16: ordinal not in range(128)". 


When the given object to be converted into json string contains only py2.7 (non-unicode) string, the value of ensure_ascii argument has no effect on the function. Detailed discussion on this issue as follows:
------------------------------------------------------------------------------------------------------------------------
Try adding the argument: ensure_ascii = False. Also especially if asking unicode-related issues it's very helpful to add a longer (complete) traceback and stating which python-version you are using.


Citing the python-documentation: of version 2.6.7 :


"If ensure_ascii is False (default: True), then some chunks written to fp may be unicode instances, subject to normal Python str to unicode coercion rules. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()) this is likely to cause an error."
So this proposal may cause new problems, but it fixed a similar problem i had. I fed the resulting unicode-String into a StringIO-object and wrrote this to a file.


Because of python 2.7 and sys.getdefaultencoding set to ascii the implicit conversion through the ''.join(chunks) statement of the json-standard-library will blow up if chunks is not ascii-encoded! You must ensure that any contained strings are converted to an ascii-compatible representation before-hand! You may try utf-8 encoded strings, but unicode-strings won't work if i'm not mistaken.
-----------------------------------------------------------------------------------------------------------------------
source: http://stackoverflow.com/questions/9693699/python-json-and-unicode


3. When py27 string (byte string) is provided as data in a requests post, the corresponding mysql connection script must contain "set char_set= 'utf8'" pseudo code.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值