gpt4 book ai didi

java - 当标签没有换行符时,如何从 html 中获取正确格式的文本

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:50 24 4
gpt4 key购买 nike

我正在尝试在 Jsoup HTML 解析库的帮助下解析这个示例 html 文件。

 <html>
<body>
<p> this is sample text</p>
<h1>this is heading sample</h1>
<select name="car" size="1">
<option value="Ford">Ford</option><option value="Chevy">Chevy</option><option selected value="Subaru">Subaru</option>
</select>
<p>this is second sample text</p>
</body>
</html>

当我仅提取文本时,我得到以下内容。

this is sample text this is heading sample FordChevySubaru this is second sample text

选项标记文本中没有空格或换行符。

如果 html 是这样的

<html>
<body>
<p> this is sample text</p>
<h1>this is heading sample</h1>
<select name="car" size="1">
<option value="Ford">Ford</option>
<option value="Chevy">Chevy</option>
<option selected value="Subaru">Subaru</option>
</select>
<p>this is second sample text</p>
</body>
</html>

现在在这种情况下,文本是这样的

this is sample text this is heading sample Ford Chevy Subaru this is second sample text

选项标签文本中带有适当的空格。如何使用第一个 html 文件获得第二个输出。即,如果标签中没有换行符,字符串怎么可能不被连接。

我在 Java 中使用以下代码。

 public static String extractText(File file) throws IOException {

Document document = Jsoup.parse(file,null);
Element body=document.body();
String textOnly=body.text();
return textOnly;
}

最佳答案

我认为满足您要求的唯一解决方案是遍历 DOM 并打印文本节点:

public static String extractText(File file) throws IOException {
StringBuilder sb = new StringBuilder();
Document document = Jsoup.parse(file, null);
Elements body = document.getAllElements();
for (Element e : body) {
for (TextNode t : e.textNodes()) {
String s = t.text();
if (StringUtils.isNotBlank(s))
sb.append(t.text()).append(" ");
}
}
return sb.toString();
}

希望有帮助。

关于java - 当标签没有换行符时,如何从 html 中获取正确格式的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991542/

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