% 定义目标URL
url = 'http://military.china.com.cn/2017-08/23/content_41458107.htm';
% 尝试读取网页内容(自动兼容新旧版本)
try
% 新版本优先使用webread
if exist('webread', 'file')
webpage = webread(url);
else
webpage = urlread(url);
end
catch e
error('网页读取失败: %s', e.message);
end
% 增强版HTML清洗流程
% 步骤1: 去除所有HTML标签(保留内容)
cleanText = regexprep(webpage, '<[^>]+>', '');
% 步骤2: 双重过滤网页链接
cleanText = regexprep(cleanText, ...
'(https?|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]', ''); % 协议型链接
cleanText = regexprep(cleanText, ...
'www\.[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]', ''); % 无协议链接
% 步骤3: 替换HTML实体字符
cleanText = regexprep(cleanText, {' ','&','"','<','>'}, {' ',' ','"','<','>'}, 'ignorecase');
% 步骤4: 清理残余符号
cleanText = regexprep(cleanText, '[■◆▼©®™●【】]', ''); % 常见网页特殊符号
% 步骤5: 规范化空白字符
cleanText = regexprep(cleanText, '\s+', ' '); % 合并多个空格
cleanText = strtrim(cleanText); % 去除首尾空格
% 保存为UTF-8编码文本文件
[fid, msg] = fopen('enhanced_output.txt', 'w', 'n', 'UTF-8');
if fid == -1
error('文件创建失败: %s', msg);
end
fprintf(fid, '%s', cleanText);
fclose(fid);
disp('增强版文本已保存为enhanced_output.txt');在这个代码基础上将文章的各个段落分开