簡體   English   中英

在 Python 中檢測爬取網站中的文本語言

[英]Detecting the language of a text from a crawled website in Python

我為不同的網站寫了幾個不同的蜘蛛output文章的文本和URL。 例子:

import scrapy
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from bs4 import BeautifulSoup

stop_words = set(stopwords.words("german"))


class FruehstueckSpider(scrapy.Spider):
    name = "fruestueckerinnen"

    def start_requests(self):
        urls = [
            'https://www.diefruehstueckerinnen.at/stadt/wien/',
        ]
        urls += [urls[0] + 'page/' + str(i) + '/' for i in range(1,17)]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hrefs = response.css('div.text > a')
        yield from response.follow_all(hrefs, callback = self.parse_attr)

    def parse_attr(self, response):

        yield {
                'text': ' '.join([i for i  in word_tokenize(re.sub(pattern='[^a-zA-Z_\-ÖöÜüÄäßèé]',string=  BeautifulSoup(response.css('.content-inner.single-content').get(),"html.parser").find(class_="content-inner single-content").text , repl=' ')) if i not in stop_words and not re.match('[0-9]', i) and len(i) >1]),
                'url': response.request.url,
        }

我想檢測整個文本的寫入語言。 將其作為另一個屬性寫在“文本”和“網址”下是否有意義? 我知道有一個來自langdetect的 function 稱為detect (輸入是一個字符串),但是在這種情況下我該如何使用它呢?

您可以像這樣在 yield 中添加另一個字段

from langdetect import detect  # add this to your import


# change the parse_attr function like this
def parse_attr(self, response):
    text = ' '.join([i for i  in word_tokenize(re.sub(pattern='[^a-zA-Z_\-ÖöÜüÄäßèé]',string=  BeautifulSoup(response.css('.content-inner.single-content').get(),"html.parser").find(class_="content-inner single-content").text , repl=' ')) if i not in stop_words and not re.match('[0-9]', i) and len(i) >1])
    language = detect(text)

    yield {
            'text': text,
            'language': language,
            'url': response.request.url,
    }

“lang”屬性是一個 html 屬性,應該定義頁面的語言。 我建議您將其用作站點的參考,因為它是識別此屬性的最直接方法。 定義此屬性是為了幫助語音軟件選擇正確的發音語言。

 <html lang="en">... </html>

將語言添加到 output 是個人喜好問題。 它不疼,但你真的需要它嗎? 您始終可以在任何地方包含但不能使用該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM