2016-11-06 56 views
3

我从网站上抓取了几篇文章,现在我试图通过从文本中删除第一部分来使语料库更具可读性。 应该删除的时间间隔在文章开始前的标签<p>Advertisement和最终标签</time>内。正如你所看到的,正则表达式应该删除多行中的几个单词。我尝试了DOTALL序列,但没有成功。正则表达式|删除给定单词前多行的单词

这是我第一次尝试:

import re 

text=''' 
<p>Advertisement</p>, <p class="byline-dateline"><span class="byline"itemprop="author creator" itemscope="" itemtype="http://schema.org/Person">By <span class="byline-author" 
data-byline-name="MILAN SCHREUER" itemprop="name">MILAN SCHREUER</span> and </span><span class="byline" 
itemid="http://topics.nytimes.com/top/reference/timestopics/people/r/alissa_johannsen_rubin/index.html" 
itemprop="author creator" itemscope="" itemtype="http://schema.org/Person"><a href="http://topics.nytimes.com/top/reference/timestopics/people/r/alissa_johannsen_rubin/index.html" 
title="More Articles by ALISSA J. RUBIN"><span class="byline-author" data-byline-name="ALISSA J. RUBIN" data-twitter-handle="Alissanyt" itemprop="name">ALISSA J. RUBIN</span></a></span><time class="dateline" content="2016-10-06T01:02:19-04:00" 
datetime="2016-10-06T01:02:19-04:00" itemprop="dateModified">OCT. 5, 2016</time> 
</p>, <p class="story-body-text story-content" data-para-count="163" data-total-count="163">BRUSSELS — A man wounded two police officers with a knife in Brussels around noon on Wednesday in what the authorities called “a potential terrorist attack.”</p>, <p class="story-body-text story-content" 
data-para-count="231" data-total-count="394">The two officers were attacked on the Boulevard Lambermont in the Schaerbeek district, just north of the city center. A third police officer, who came to their aid, was also injured. None of the three had life-threatening injuries.</p> 
''' 
my_pattern=("(.*)</time>") 
results= re.sub(my_pattern," ", text) 
print(results) 

回答

3

试试这个:

my_pattern=("[\s\S]+\<\/time\>") 

如果你也想还删除以下标签</p>,逗号,和空间,你可以使用这个:

my_pattern=("[\s\S]+\<\/time\>[\s\S]\<\/p\>\,\s") 
+0

如果我想省略第一个标签怎么办

广告

及其属性? –

+0

@ M.Huntz你尝试这样的事情'(?<=\<\/p\>)\ S \ S] + \ <\/time\>'或'这个(?<=\<\/p\>)\ S \ S] + \ <\/time\> [\ S \ S] \ <\/p\> \ ,\ s'演示:https://regex101.com/r/79n80Z/3 – Ibrahim