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

时间:2013-05-15 03:59:58

标签: javascript regex parsing nlp text-segmentation

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

<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被注入到它接触到的任何页面中并动态解析<p>标签。因此,它需要是javascript。

1 个答案:

答案 0 :(得分:0)

肥皂盒

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

然而

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

(<[^>]*>)

enter image description here enter image description here

保留句子,包括子标题

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

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

  • (<p(?:\s[^>]*)?>)(.*?)(</p>) - 捕获打开和关闭段落标记以及包含任何子标记的innertext

当然这些是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>