64 lines
3.0 KiB
Java
64 lines
3.0 KiB
Java
import org.jsoup.Jsoup;
|
|
import org.jsoup.nodes.Document;
|
|
import org.jsoup.nodes.Element;
|
|
import org.jsoup.select.Elements;
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.util.*;
|
|
|
|
public class Parser {
|
|
// لیستی برای ذخیره کردن فیلمهای استخراج شده از HTML
|
|
private List<Movie> movies = new ArrayList<>();
|
|
|
|
public Parser(String filePath) throws IOException {
|
|
setUp(filePath);
|
|
}
|
|
|
|
//مرتبسازی فیلمها به صورت الفبایی بر اساس عنوان (A تا Z)
|
|
public List<Movie> sortByTitle() {
|
|
List<Movie> sortedByTitle = new ArrayList<>(movies);
|
|
sortedByTitle.sort(Comparator.comparing(Movie::getTitle));
|
|
return sortedByTitle;
|
|
}
|
|
|
|
//مرتب سازی فیلمها بر اساس امتیاز به صورت نزولی (بیشترین به کمترین)
|
|
public List<Movie> sortByRating() {
|
|
List<Movie> sortedByRating = new ArrayList<>(movies);
|
|
sortedByRating.sort(Comparator.comparingDouble(Movie::getRating).reversed());
|
|
return sortedByRating;
|
|
}
|
|
|
|
//مرتب سازی فیلمها بر اساس سال ساخت به صورت نزولی (جدیدترین به قدیمیترین)
|
|
public List<Movie> sortByYear() {
|
|
List<Movie> sortedByYear = new ArrayList<>(movies);
|
|
sortedByYear.sort(Comparator.comparingInt(Movie::getYear).reversed());
|
|
return sortedByYear;
|
|
}
|
|
|
|
// متد اصلی بارگذاری فایل و استخراج اطلاعات فیلمها با JSoup
|
|
private void setUp(String filePath) throws IOException {
|
|
// باز کردن فایل HTML از روی مسیر داده شده و پارس کردن ساختار آن
|
|
File file = new File(filePath);
|
|
Document document = Jsoup.parse(file, "UTF-8");
|
|
|
|
// پیدا کردن تمام بلاکهای مربوط به فیلمها که کلاس "movie" دارند
|
|
Elements movieElements = document.getElementsByClass("movie");
|
|
|
|
// پیمایش تکتک فیلمها برای بیرون کشیدن جزئیات
|
|
for (Element element : movieElements) {
|
|
// استخراج عنوان فیلم از تگ h3
|
|
String title = element.selectFirst("h3.movie-title").text();
|
|
|
|
// استخراج امتیاز و حذف بخش اضافی "/10" برای تبدیل راحت به عدد اعشاری
|
|
String ratingText = element.selectFirst("span.movie-rating").text();
|
|
double rating = Double.parseDouble(ratingText.replace("/10", "").trim());
|
|
|
|
// استخراج سال ساخت و تبدیل متن به عدد صحیح (int)
|
|
String yearText = element.selectFirst("span.movie-year").text();
|
|
int year = Integer.parseInt(yearText.trim());
|
|
|
|
// ساخت شیء فیلم جدید و اضافه کردن آن به لیست اصلی
|
|
movies.add(new Movie(title, rating, year));
|
|
}
|
|
}
|
|
} |