[英]How to get the specific tag where the text matches most of the words in a given list of words using JSOUP?
我正在嘗試獲取在給定的單詞列表中具有最大字匹配數的整個標記! 即: 考慮html:
<div id="productTitle" class="a-size-large">Hello world, good morning, have a happy day</div> <div id="productTitle2" class="a-size-large">Hello people of this planet!.</div>
考慮使用jsoup lib的java代碼:
String html = "<div id="productTitle" class="a-size-large">Hello world, good morning, have a happy day</div> <div id="productTitle2" class="a-size-large">Hello people of this planet!.</div>";
Document doc = Jsoup.parse(html);
List<String> words = new ArrayList<>(Arrays.asList("hello", "world", "morning"));
Element elmnt = doc.select("*:matchesOwn("+words+")");
System.out.println(elmnt.cssSelector());
預期輸出: #productTitle
不幸的是,沒有像這樣的選擇器。 您可以創建一個小算法來代替:
使用Document.getAllElements()
獲取Document.getAllElements()
中所有元素的列表。 要獲取元素的實際文本,請使用Element.ownText()
。 現在,您可以將該文本拆分為單詞並計算所有單詞:
String html = "<div id=\"productTitle\" class=\"a-size-large\">Hello world, good morning, have a happy day</div> <div id=\"productTitle2\" class=\"a-size-large\">Hello people of this planet!.</div>";
Document doc = Jsoup.parse(html);
List<String> words = Arrays.asList("hello", "world", "morning");
Element elmnt = doc.getAllElements().stream()
.collect(Collectors.toMap(e -> countWords(words, e.ownText()), Function.identity(), (e0, e1) -> e1, TreeMap::new))
.lastEntry().getValue();
這使用Java Streams和TreeMap
將單詞數TreeMap
到元素。 如果兩個或多個元素具有相同數量的單詞,則使用最后一個單詞。 我想使用你可以使用的第一個(e0, e1) -> e0
。
要計算列表中給出的單詞,您還可以使用Java Streams。 你可以使用這樣的方法:
private long countWords(List<String> words, String text) {
return Arrays.stream(text.split("[^\\w]+"))
.map(String::toLowerCase)
.filter(words::contains)
.count();
}
這將拆分所有非單詞字符的文本。 您可以根據自己的需要進行更改。
您共享的HTML代碼的elmnt.cssSelector()
的結果將是#productTitle
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.