1 changed files with 71 additions and 0 deletions
@ -0,0 +1,71 @@ |
|||
package com.example.datacollect.command; |
|||
|
|||
import com.example.datacollect.model.Article; |
|||
import com.example.datacollect.repository.ArticleRepository; |
|||
import com.example.datacollect.strategy.CrawlStrategy; |
|||
import com.example.datacollect.strategy.StrategyFactory; |
|||
import com.example.datacollect.view.ConsoleView; |
|||
import org.jsoup.Jsoup; |
|||
import org.jsoup.nodes.Document; |
|||
|
|||
import java.util.List; |
|||
|
|||
public class AnalyzeCommand implements Command { |
|||
private final ConsoleView view; |
|||
private final StrategyFactory strategyFactory; |
|||
|
|||
public AnalyzeCommand(ConsoleView view, StrategyFactory strategyFactory) { |
|||
this.view = view; |
|||
this.strategyFactory = strategyFactory; |
|||
} |
|||
|
|||
@Override |
|||
public String getName() { |
|||
return "analyze"; |
|||
} |
|||
|
|||
@Override |
|||
public void execute(String[] args, ArticleRepository repository) { |
|||
if (args.length < 2) { |
|||
view.printError("Usage: analyze <url>"); |
|||
return; |
|||
} |
|||
String url = args[1]; |
|||
|
|||
CrawlStrategy strategy = strategyFactory.getStrategy(url); |
|||
if (strategy == null) { |
|||
view.printError("No strategy found for: " + url); |
|||
return; |
|||
} |
|||
|
|||
try { |
|||
view.printInfo("Analyzing: " + url); |
|||
Document doc = Jsoup.connect(url).get(); |
|||
List<Article> articles = strategy.parse(url, doc); |
|||
|
|||
int articleCount = articles.size(); |
|||
int totalTitleLength = 0; |
|||
int maxTitleLength = 0; |
|||
int minTitleLength = Integer.MAX_VALUE; |
|||
|
|||
for (Article article : articles) { |
|||
int len = article.getTitle().length(); |
|||
totalTitleLength += len; |
|||
maxTitleLength = Math.max(maxTitleLength, len); |
|||
minTitleLength = Math.min(minTitleLength, len); |
|||
} |
|||
|
|||
view.printSuccess("=== 分析结果 ==="); |
|||
view.printInfo("文章数量: " + articleCount); |
|||
if (articleCount > 0) { |
|||
view.printInfo("标题总长度: " + totalTitleLength); |
|||
view.printInfo("平均标题长度: " + String.format("%.2f", (double) totalTitleLength / articleCount)); |
|||
view.printInfo("最长标题: " + maxTitleLength + " 字符"); |
|||
view.printInfo("最短标题: " + minTitleLength + " 字符"); |
|||
} |
|||
|
|||
} catch (Exception e) { |
|||
view.printError("Failed to analyze: " + e.getMessage()); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue