【问题标题】:Splitting HTML Content Into Sentences, But Keeping Subtags Intact将 HTML 内容拆分为句子,但保持子标签完整
【发布时间】:2026-01-15 14:10:01
【问题描述】:

我正在使用下面的代码将段落标签中的所有文本分成句子。除了少数例外,它工作正常。但是,段落中的标签会被咀嚼并吐出。示例:

<p>This is a sample of a <a href="#">link</a> getting chewed up.</p>

那么,我怎样才能忽略标签,这样我就可以解析句子并在它们周围放置 span 标签并保持 , 等...标签在适当的位置? 或者以某种方式走更聪明DOM 并这样做?

// Split text on page into clickable sentences
$('p').each(function() {
    var sentences = $(this)
        .text()
        .replace(/(((?![.!?]['"]?\s).)*[.!?]['"]?)(\s|$)/g, 
                 '<span class="sentence">$1</span>$3');
    $(this).html(sentences);
});

我在 Chrome 扩展内容脚本中使用它;这意味着 javascript 被注入到它所接触的任何页面中,并动态解析 &lt;p&gt; 标签。因此,它需要是javascript。

【问题讨论】:

  • 所以您是说您拥有的代码工作正常,但您想知道是否有其他方法可以实现相同的效果?我并没有真正遵循你想要的,或者问题是什么。
  • 为了清楚起见,我的问题加粗了。我需要做我现在正在做的事情,但将所有标签保留在我正在搜索的

    标签中,以便图像、链接等...保持原样。

  • 编辑了我的问题,以反映我在 chrome 扩展内容脚本中使用它的事实。
  • 那么你对这样的事情有什么期待呢? '

    这是一个“.”的样本。在 一些元素内。您的预期结果是什么

    '

标签: javascript regex parsing nlp text-segmentation


【解决方案1】:

肥皂盒

我们可以制作一个正则表达式来匹配您的具体情况,但鉴于这是 HTML 解析,并且您的用例暗示其中可能包含任意数量的标签,您最好使用 DOM 或使用类似的产品HTML Agility (free)

然而

如果您只是想提取内部文本并且对保留任何标记数据不感兴趣,您可以使用此正则表达式并将所有匹配项替换为 null

(&lt;[^&gt;]*&gt;)

保留句子,包括子标签

  • ((?:&lt;p(?:\s[^&gt;]*)?&gt;).*?&lt;/p&gt;) - 保留段落标签和整个句子,但不保留段落之外的任何数据

  • (?:&lt;p(?:\s[^&gt;]*)?&gt;)(.*?)(?:&lt;/p&gt;) - 只保留包含所有子标签的段落内部文本,并将句子存储到第 1 组中

  • (&lt;p(?:\s[^&gt;]*)?&gt;)(.*?)(&lt;/p&gt;) - 捕获打开和关闭段落标签以及包含任何子标签的内文

这些是 PowerShell 示例,正则表达式和替换函数应该类似

$string = '<img> not this stuff either</img><p class=SuperCoolStuff>This is a sample of a <a href="#">link</a> getting chewed up.</p><a> other stuff</a>'

Write-Host "replace p tags with a new span tag"
$string -replace '(?:<p(?:\s[^>]*)?>)(.*?)(?:</p>)', '<span class=sentence>$1</span>'

Write-Host
Write-Host "insert p tag's inner text into a span new span tag and return the entire thing including the p tags"
$string -replace '(<p(?:\s[^>]*)?>)(.*?)(</p>)', '$1<span class=sentence>$2</span>$3'

产量

replace p tags with a new span tag
<img> not this stuff either</img><span class=sentence>This is a sample of a <a href="#">link</a> getting chewed up.</span
><a> other stuff</a>

insert p tag's inner text into a span new span tag and return the entire thing including the p tags
<img> not this stuff either</img><p class=SuperCoolStuff><span class=sentence>This is a sample of a <a href="#">link</a> 
getting chewed up.</span></p><a> other stuff</a>

【讨论】:

  • 您能否澄清一下,也许将您的答案与我的正则表达式结合起来?
  • 看起来您想从标签中提取句子字符串并将其替换为一组跨度标签。所以我建议您捕获该段落,然后删除任何嵌入的标签数据。这个新值是我要插入到您的跨度标签中的值
  • 我绝对需要保留标签数据,以便链接、图像等...在段落中工作。