Newspaper:利用 Python 进行新闻文章抓取与内容策划

Newspaper 是一个用于提取和解析新闻文章的 Python 模块。它结合了先进的算法和网络爬虫技术,能够从网站中提取所有有用的文本内容。它在在线新闻网站上表现得非常出色。不过,由于它使用了网络爬虫技术,如果我们在短时间内对某个新闻网站发起过多请求,可能会导致 IP 被封锁,因此请务必合理使用。

安装

pip install newspaper3k

Newspaper 支持以下语言:

****input codefull name****
  ar               Arabic (阿拉伯语)
  da               Danish (丹麦语)
  de               German (德语)
  el               Greek (希腊语)
  en               English (英语)
  it               Italian (意大利语)
  zh               Chinese (中文)
......... and many more (以及更多)

当我们从网站(尤其是新闻媒体)抓取文章时,经常会遇到结构混乱或排版不规范的 HTML 内容。这使得从页面中提取有意义的数据变得困难。幸运的是,结合使用 newspaper3k 和 lxmlhtmlclean 可以提供一种高效的方式来清洗和处理网页内容,从而让我们能更准确地提取文章正文、标题、摘要和关键词。

安装 lxmlhtmlclean

我们可以使用以下命令来安装 lxmlhtmlclean 库:

Python


CODEBLOCK_b38391c4

这将安装该库及其依赖项(包括 lxml),lxml 是 Python 中一个功能强大且高效的 XML 和 HTML 处理库。

Missing punkt Data for NLP: (NLP 缺失 punkt 数据)

如果我们遇到了与 punkt 数据缺失相关的错误(例如:LookupError: Resource punkt not found),可以通过下载必要的 NLTK 资源来解决。

  • 运行以下代码来下载所需的 punkt 分词器:

Python


CODEBLOCK_0d4279e6

  • 如果错误与缺失的 punkt_tab 相关,请尝试运行:

Python


CODEBLOCK_3599fec1

这将确保分词器可用,以满足 nlp() 等 NLP 函数进行句子分割的需求。

> 注意: 如果我们的系统或环境中已经安装了 INLINECODEd6020b42 或 INLINECODE5960428d,则无需手动导入它们。如果它们已经预装,将会被内部调用。但是,如果在运行代码时遇到任何错误或问题,请尝试手动导入这两个库并下载必要的 NLTK 资源(如 INLINECODE01617c57 和 INLINECODE217223fc),以确保环境中存在所有必需的依赖项。

创建文章实例的一些实用函数

article_name = Article(url, language="language code according to newspaper")

下载文章

article_name.download()

解析文章

article_name.parse()

对文章应用 nlp(自然语言处理)

article_name.nlp()

提取文章正文

article_name.text

提取文章标题

article_name.title

提取文章摘要

article_name.summary

提取文章关键词

article_name.keywords

Python


CODEBLOCK_09174f46

输出: (Output)

“`

Article‘s Title:

India China News: Chinese expert warns of troops entering Kashmir

Article‘s Text:

BEIJING: A Chinese expert has argued that his country‘s troops would be entitled to enter the Indian side of Kashmir by extending the logic that has permitted Indian troops to enter an area which is disputed by China and Bhutan This is one of the several arguments made by the scholar in an attempt to blame India for. India has responded to efforts by China to build a road in the Doklam area, which falls next to the trijunction connecting Sikkim with Tibet and Bhutan and"Even if India were requested to defend Bhutan‘s territory, this could only be limited to its established territory, not the disputed area, " Long Xingchun, director of the Center for Indian Studies at China West Normal University said in an article. "Otherwise, under India‘s logic, if the Pakistani government requests, a third country‘s army can enter the

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/29703.html
点赞
0.00 平均评分 (0% 分数) - 0