ano*_*428 5 java regex web-crawler
public class Parser {
public static void main(String[] args) {
Parser p = new Parser();
p.matchString();
}
parserObject courseObject = new parserObject();
ArrayList<parserObject> courseObjects = new ArrayList<parserObject>();
ArrayList<String> courseNames = new ArrayList<String>();
String theWebPage = " ";
{
try {
URL theUrl = new URL("http://ocw.mit.edu/courses/");
BufferedReader reader =
new BufferedReader(new InputStreamReader(theUrl.openStream()));
String str = null;
while((str = reader.readLine()) != null) {
theWebPage = theWebPage + " " + str;
}
reader.close();
} catch (MalformedURLException e) {
// do nothing
} catch (IOException e) {
// do nothing
}
}
public void matchString() {
// this is my regex that I am using to compare strings on input page
String matchRegex = "#\\w+(-\\w+)+";
Pattern p = Pattern.compile(matchRegex);
Matcher m = p.matcher(theWebPage);
int i = 0;
while (!m.hitEnd()) {
try {
System.out.println(m.group());
courseNames.add(i, m.group());
i++;
} catch (IllegalStateException e) {
// do nothing
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想用上面的代码实现的是获取麻省理工学院开放式课程网站上的部门列表.我正在使用与页面源中的部门名称模式匹配的正则表达式.我正在使用Pattern对象和Matcher对象,并尝试查找()并打印与正则表达式匹配的这些部门名称.但代码正在运行,我不认为使用bufferedReader在网页中阅读需要那么长时间.所以我认为我要么做一些可怕的错误,要么解析网站需要花费相当长的时间.所以如果有任何关于如何提高性能或纠正我的代码中的错误,我将不胜感激.我为编写糟糕的代码道歉.
Stu*_*rks 13
问题在于代码
while ((str = reader.readLine()) != null)
theWebPage = theWebPage + " " +str;
Run Code Online (Sandbox Code Playgroud)
变量theWebPage是一个String,它是不可变的.对于读取的每一行,此代码创建一个新的 String,其中包含到目前为止已读取的所有内容的副本,并附加一个空格和刚刚读取的行.这是一个非常多的不必要的复制,这就是程序运行如此缓慢的原因.
我下载了有问题的网页.它有55,000行,大小约为3.25MB.不太大.但由于循环中的复制,第一行最终被复制约15亿次(55,000平方的1/2).该计划花费所有时间进行复制和垃圾收集.我在笔记本电脑上运行了这个(2.66GHz Core2Duo,1GB堆),从本地文件读取时运行了15分钟(没有网络延迟或网络爬行对策).
为了解决这个问题,使theWebPage成一个StringBuilder,而是和改线的循环中
theWebPage.append(" ").append(str);
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以在循环后theWebPage使用转换为String toString().当我运行修改后的版本时,花了不到一秒钟.
顺便说一句,你的代码{ }在一个类中使用了一个裸代码块.这是一个实例初始化器(与静态初始化器相对).它在对象构建时运行.这是合法的,但这很不寻常.请注意,它误导了其他评论者.我建议将此代码块转换为命名方法.
| 归档时间: |
|
| 查看次数: |
737 次 |
| 最近记录: |