gpt4 book ai didi

java - 从 Jsoup 抓取的文本中删除多个字符 10

转载 作者:行者123 更新时间:2023-12-01 10:34:27 25 4
gpt4 key购买 nike

我有相当多的文件(大约 600 个),其中包含我用 Jsoup 抓取的文本。该文本仅包含 <p> 内的 HTML和<br>尝试在文本中保留一些段落。问题在于,在某些文件中存在一长串新行,Java 将这些新行读取为字符 10。在某些情况下,可能会超过 30 个新行,例如有人按 Enter 键却卡住了。

我知道,由于 <br> 导致换行,这主要是我的错。标签,但无法找到一种方法来仅保留一个换行符并在抓取时放弃其余部分。

这是我正在使用的 Jsoup 代码的一部分(来自 How do I preserve line breaks when using jsoup to convert html to plain text? )

Document document = Jsoup.connect(url).get();
document.outputSettings(new Document.OutputSettings().prettyPrint(false));//preserve html linebreaks
document.select("br").append("\\n");
document.select("p").prepend("\\n\\n");
document.select(":containsOwn(\u00a0)").remove();
String s = document.html().replaceAll("\\\\n", "\n");
String txtOnly = Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));

是否可以以某种方式清理文件的内容,而无需实际重新运行抓取过程?我尝试使用 HashSet 只保留一个字符 10,然后当到达行尾时,打印该集合中唯一的字符 10。但不知怎么的,它并没有起作用。

关于如何执行此操作有什么好的建议吗?

最佳答案

在 HTML 中,所有由 1 个或多个空白字符组成的序列(包括换行符,如字符 10)都相当于一个空格。您可以使用正则表达式将连续的空白字符替换为单个空格。 然后进行
替换以在适当的位置插入换行符。

public static void processHtml(String html) {
html = normalizeHtmlWhitespace(html);
html = html.replace("<br>", "\n");
// more robust code would use a real HTML parser to do the <br> replacement
}

public static String normalizeHtmlWhitespace(String html) {
return html.replaceAll("\\s+", " ");
}

关于java - 从 Jsoup 抓取的文本中删除多个字符 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34864215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com