如何用python检测网页内容的语言

2024-09-22 22:32:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我要测试一堆网址,这些网页是否有各自的翻译内容。有没有办法用Python语言返回网页内容的语言?就像如果页面是中文的,那么它应该返回“Chinese”`。在

我用langdetect模块检查了它,但是没有得到我想要的结果。这些url是webxml格式的。内容显示在<releasehigh>


Tags: 模块语言url网页内容格式页面网址
3条回答

您可以提取内容块,然后使用一些python语言检测,如langdetect或{a2}。在

下面是一个简单的示例,演示如何使用BeautifulSoup提取HTML正文文本,langdetect用于语言检测:

from bs4 import BeautifulSoup
from langdetect import detect

with open("foo.html", "rb") as f:
    soup = BeautifulSoup(f, "lxml")
    [s.decompose() for s in soup("script")]  # remove <script> elements
    body_text = soup.body.get_text()
    print(detect(body_text))

也许你有这样一个标题:

<HTML xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">

如果是这种情况,您可以用lang=“fr”看到这是一个法语网页。如果不是这样的话,猜测一篇文章的语言并不是件小事。在

相关问题 更多 >