【问题标题】:How to remove multiple tags from a text file using python's regex如何使用 python 的正则表达式从文本文件中删除多个标签
【发布时间】:2021-06-07 21:54:24
【问题描述】:

新手来了!我正在使用 Python 3.8.3 并试图从附加的文本文件中删除标签listfile.txt

我想提取 3 个列表 - 文章的标题、出版日期和正文并删除标签。在下面的代码中,我已经能够从标题和出版日期中删除标签。但是,我无法从正文中正确删除所有标签。在文件中,正文以标签<div class="story-element story-element-text"> 开始,在下一个

任何帮助提取这部分文本将不胜感激!文章文本是非英文脚本,但所有的html标签都是英文的。

#opening text file which contains newspaper article information scraped off website using beautifulsoup
with open('listfile.txt', 'r', encoding='utf8') as my_file:
    text = my_file.read()
    print(text)  

#removing tags and generating list of newspaper article titles    
titles = re.findall('<h1.*?>(.*?)</h1>', text)
print(titles) 

#removing tags and generating list of newspaper article publication dates 
dates = re.findall('<div class=\"storyPageMetaData-m__publish-time__19bdV\"><span>(.*?)</span>', text)
print(dates)

#removing tags and generating list containing main text of articles. This is where the code is incorrect
bodytext= re.findall('<div class=\"story-element story-element-text\">(.*?)</div>', text)
print(bodytext)

【问题讨论】:

标签: python python-3.x regex tags findall


【解决方案1】:

我认为你使用了错误的工具, 我建议你改用bs4;我保证你会喜欢的?。

from bs4 import BeautifulSoup
raw_html = "YOUR RAW HTML"
soup = BeautifulSoup(raw_html, "html.parser")
titles = [h1_tag.text for h1_tag in soup.select('h1')]
dates = [span_tag.text for span_tag in soup.select('div.storyPageMetaData-m__publish-time__19bdV > span')]
bodytext = [div_tag.text for div_tag in soup.select('div.story-element.story-element-text')]

享受?

【讨论】:

  • 谢谢!此代码适用于标题和日期,但没有让我了解所有正文。在该文件中,正文文本从 div.story-element.story-element-text 的第一个实例开始,并在下一个 h1 标记之前结束。有什么办法可以修改代码吗?
  • 例如,使用 bodytext[0],我只得到第一篇文章的第一段,而不是第一篇文章的全部。使用 bodytext[1],我得到了第一篇文章的第二段,但我应该得到第二篇文章,对吧?
【解决方案2】:

我不熟悉如何在 python 中设置正则表达式,但这适用于 JavaScript

如果您仍想使用 RegEx,请使用它来捕获文本文件中的 h1 标签。 &lt;h1(.*?)&lt;/h1&gt;

``

【讨论】:

    猜你喜欢
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多