8000 [java] Replace `wholeText()` with `NodeVisitor` by kojiishi · Pull Request #369 · google/budoux · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

[java] Replace wholeText() with NodeVisitor #369

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions java/src/main/java/com/google/budoux/HTMLProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,31 @@ private HTMLProcessor() {}
}
}

/**
* A `NodeVisitor` subclass that concatenates all `TextNode`s to a string.
*
* <p>It also converts `&lt;br>` to `\n`.
*/
private static class TextizeNodeVisitor implements NodeVisitor {
private StringBuilder output = new StringBuilder();

public String getString() {
return output.toString();
}

@Override
public void head(Node node, int depth) {
if (node instanceof Element) {
final String nodeName = node.nodeName();
if (nodeName.equals("br")) {
output.append('\n');
}
} else if (node instanceof TextNode) {
output.append(((TextNode) node).getWholeText());
}
}
}

private static class PhraseResolvingNodeVisitor implements NodeVisitor {
private static final char SEP = '\uFFFF';
private final String phrasesJoined;
Expand Down Expand Up @@ -97,12 +122,11 @@ public void head(Node node, int depth) {
.map(attribute -> " " + attribute)
.collect(Collectors.joining(""));
final String nodeName = node.nodeName();
final String upperNodeName = nodeName.toUpperCase(Locale.ENGLISH);
if (upperNodeName.equals("BR")) {
// Match jsoup `Element.wholeText()` returning `\n` for `<br>`.
if (nodeName.equals("br")) {
// `<br>` is converted to `\n`, see `TextizeNodeVisitor.head`.
// Assume phrasesJoined.charAt(scanIndex) == '\n'.
scanIndex++;
} else if (skipNodes.contains(upperNodeName)) {
} else if (skipNodes.contains(nodeName.toUpperCase(Locale.ENGLISH))) {
if (!toSkip && phrasesJoined.charAt(scanIndex) == SEP) {
output.append(separator);
scanIndex++;
Expand Down Expand Up @@ -175,6 +199,9 @@ public static String resolve(List<String> phrases, String html, String separator
* @return the text content.
*/
public static String getText(String html) {
return Jsoup.parseBodyFragment(html).wholeText();
Document doc = Jsoup.parseBodyFragment(html);
TextizeNodeVisitor nodeVisitor = new TextizeNodeVisitor();
doc.body().traverse(nodeVisitor);
return nodeVisitor.getString();
3B69 }
}
0