【问题标题】:How to reconstruct a String correctly from a String which be encoded by wrong charset如何从由错误字符集编码的字符串正确重建字符串
【发布时间】:2012-11-12 09:22:02
【问题描述】:

编辑添加了一些新信息以使问题更清晰。

在 2012B 之前的 matlab 中,如果 Web 内容的字符集不是 utf8,则方法 urlread 将返回由错误字符集构造的字符串。 (在 Matlab 2012B 中有所改进)

例如

% a chinese website whose content encoding by gb2312
url = 'http://www.cnbeta.com/articles/213618.htm'; 
html = urlread(url)

因为 Matlab 使用 utf8 而不是 gb2312 对 html 进行编码。 您会看到 html 中的汉字显示不正确。

如果我阅读一个 utf8 编码的中文网站,那么一切正常:

% a chinese website whose content encoding by utf8
url = 'http://www.baidu.com/'; 
html = urlread(url)

那么有没有办法从 html 中正确地重构字符串? 我尝试了以下方法,但没有奏效:

>> bytes = unicode2native(html,'utf8');
>> str = native2unicode(bytes,'gb2312')

但是,我知道有一种方法可以解决 urlread 的问题: 在控制台中输入edit urlread.m,然后在第108行附近替换代码(在matlab 2011B中):

output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),'UTF-8');

作者:

output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),'gb2312');

保存文件,现在urlread 将适用于由 gb2312 编码的网站。 实际上,这个解决方案指出了为什么 urlread 有时不起作用。方法urlread 始终使用utf8 字符集对字符串进行编码,即使内容不是utf8 编码的。

【问题讨论】:

  • 到底是什么问题?看来你已经有了解决办法,只需创建一个名为 urlread_gb 的函数,它可以读取 gb2312。
  • 好孩子们,同样的问题...有可能以更“更好”的方式进行这种转换吗?

标签: matlab encoding urlread


【解决方案1】:

看来你已经有了解决办法,只需创建一个名为urlread_gb 的函数,它可以读取gb2312

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 2016-09-30
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多