2

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

在 2012B 之前的 matlab 中,urlread如果 Web 内容的字符集不是 utf8,该方法将返回由错误字符集构造的字符串。(在 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's 的问题: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 编码的。

4

1 回答 1

0

看来您已经有了解决方案,只需创建一个名为的函数urlread_gb即可读取gb2312.

于 2013-05-28T15:59:32.470 回答