正则表达式|删除给定单词前多行的单词

时间:2016-11-06 16:24:27

标签: regex python-3.x

我从一个网站上抓了几篇文章,现在我试图通过删除文本中的第一部分来使语料库更具可读性。 在文章开始之前,应删除的时间间隔位于代码<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)

1 个答案:

答案 0 :(得分:3)

试试这个:

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

如果您还要删除以下标记</p>,逗号,和空格,则可以使用此标记:

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