Matlab使用urlread()读取网页乱码问题.docx
文本预览下载声明
Matlab使用urlread()读取网页乱码问题??事先声明这是本人在网上找到的(/2012-05/matlaburlread.html),非原创:Matlab的urlread()函数可以读取网页,调用语法:S = urlread(URL,method,PARAMS)共有三个参数,第一个是网页地址,第二个是get或是post,意思很直白;第三个则是要向网页传递的参数,详细见help文档。本博文的这个问题不是重点。重点在于,用这个读取中文网页会乱码。例如:S=urlread();自己去看S的内容,里面凡是应该是中文文字的部分都是问号。?3年前,我写Matlab基础班讲义的时候实际已经把这个问题解决了,但是没有记录下来,这次又遇上同样的问题,一下子记不起来了(翻开当年讲义,看到自己写到“这个问题可以通过手工修改urlread()函数解决”,感到很愤慨,多写一句我就不用费那劳什子的精神了)?废话打住,下面开工修理urlread()函数,让它能够正常搞中文网页(注我用的是2012A版本,其他版本可能有变化)。在Matlab中输入 edit urlread打开函数代码文件。修改1: ?修改第一行的函数定义,本来是三个参数,在最后添加一个。例如,我修改后:function [output,status] = urlread(urlChar,method,params,webencoding)在下面添加一句if nargin4; webencoding=UTF-8; end作用是与修改前的函数调用语法兼容。修改2:修改参数数量检验语句,该语句位于文件中偏前部,例如原来是narginchk(1,3)改为narginchk(1,4)修改3:修改文件尾部的数据转换语句,它原本是:output = native2unicode(typecast(byteArrayOutputStream.toByteArray,uint8),UTF-8);用webencoding替换UTF-8,注意包括单引号也要替换。搞定了,然后再读取网页。一般中文网页的网页编码是GBK(兼容’GB2312),调用语法是:S=urlread(,get,,GBK)这样返回来的文字里面就可以正常显示中文了。为了方便大家修改,我把改好后的代码和未改的原代码放在了下一页,就这一点是比原文多的,也是害怕自己忘了。要是嫌麻烦,就把下一页的代码复制粘贴过去,覆盖源代码,不过别忘了把原代码保留一份,免得忘了怎么改回来。修改后的代码:function [output,status] = urlread(urlChar,method,params,webencoding)if nargin4; webencoding=UTF-8;end%URLREAD Returns the contents of a URL as a string.% S = URLREAD(URL) reads the content at a URL into a string, S. If the% server returns binary data, the string will contain garbage.%% S = URLREAD(URL,method,PARAMS) passes information to the server as% part of the request. The method can be get, or post and PARAMS is a % cell array of param/value pairs.%% [S,STATUS] = URLREAD(...) catches any errors and returns 1 if the file% downloaded successfully and 0 otherwise.%% Examples:% s = urlread()% s = urlread(/README)% s = urlread([file:/// fullfile(prefdir,history.m)])% % From behind a firewall, use the Preferences to set your proxy server.%% See also URLWRITE.% Matthew J. Simoneau, 13-Nov-2001% Copyright 1984-2008 The MathWorks, Inc.% $Revision: 0 $ $Date: 2008/10/02 18:59:57 $% This function require
显示全部