You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.4 KiB
71 lines
2.4 KiB
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());
|
|
}
|
|
}
|
|
}
|