javascript - 将 HTML 内容拆分成句子,但保持子标签完整

标签 javascript regex parsing nlp text-segmentation

我正在使用下面的代码将段落标记中的所有文本分隔成句子。除了少数异常(exception),它工作正常。然而,段落中的标签被咀嚼并吐出。示例:

<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 被注入(inject)到它接触的任何页面并解析 <p>即时标记。因此,它需要是javascript。

最佳答案

肥皂盒

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

然而

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

(<[^>]*>)

enter image description here enter image description here

保留句子原样,包括子标签

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

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

  • (<p(?:\s[^>]*)?>)(.*?)(</p>) - 捕获开始和结束段落标签和包含任何子标签的内部文本

假设这些是 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>

关于javascript - 将 HTML 内容拆分成句子,但保持子标签完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16556598/

相关文章:

javascript - Django 对 Javascript 文件翻译的支持

java - 拆分字符串 ('_' 作为分隔符)

javascript - Angularjs 中的日期选择器值转换为字符串

javascript - 如何添加地理编码服务(对于 MapBox)

mysql - 带有正则表达式的 SQL Like 语句

mysql - 使用 RegExp 缩短 MySQL SELECT

C++ 使用 STD 解析 XML

python - 当存在另一个带有文本的标签时,lxml 库不会提取给定 html 标签中的文本

javascript - 无法在 Angular 2 中验证用户身份

c# - 正则表达式替换除斜杠以外的所有特殊字符?