Веб-парсинг с python из онлайн-словаря (Reverso context) - PullRequest
1 голос
/ 18 июня 2020

Я хочу создать программу, которая ищет введенный список слов на немецком языке и находит их в Reverso Context с соответствующими примерами этих слов. После их нахождения введенные слова будут удалены, а примеры будут представлены без этих слов. Я пробовал делать это, но одним словом:

import requests
from bs4 import BeautifulSoup

inp = input("Type a german word\n")

web = requests.get('https://context.reverso.net/translation/german-english/'+inp)

data = web.content

soup = BeautifulSoup(data, features = "html.parser")

tag = soup.find_all("span","text","de")

a = 1
for i in tag:
    print(a, ".", i.text)
    a = a+1

помогите соответствовать требованиям, которые я написал, пожалуйста.

Ответы [ 2 ]

0 голосов
/ 10 июля 2020

Я реализовал оболочку python для Reverso Context API: https://github.com/flagist0/reverso_context_api

В вашем случае вы можете использовать это так:

from itertools import islice
from reverso_context_api import Client

def get_samples(client, word, num=5):
    # There can be thousands of translation samples, this function requests and returns only needed amount of them
    iterator = client.get_translation_samples(word)
    return list(islice(iterator, num))

client = Client(source_lang="de", target_lang="en")
# call get_samples for each word in your list
print(get_samples(client, "Fortschritt"))

# Outputs:
# [('Überprüfen Sie den Fortschritt des Datenbank-Loaders im Prozessmanager.',
#   'Check the progress of the Database Loader in your Process Manager.'),
#  ('Status verfolgen auch den Fortschritt des Auftragsabschlussprozesses.',
#   'Statuses also track the progress of the job close process.'),
#  ('Kommissar Vitorino hatte das Abkommen als großen Fortschritt bezeichnet.',
#   "Commissioner Vitorino has described it as a 'major advance'."),
#  ('Dies ist deshalb schon ein großer Fortschritt.',
#   'This is, therefore, already a major advance.'),
#  ('Ich betrachte die Charta als akzeptablen Fortschritt.',
#   'I consider that the Charter of Fundamental Rights represents a valuable step forward.')]
0 голосов
/ 18 июня 2020

На каждой итерации вы можете увидеть это сообщение Please enter the word to collect the data or you want to end the prosecc, enter the charcter 'e': или вы можете сделать list of word и, в противном случае, вы получите тот же результат. Вы можете попробовать:

import requests
from bs4 import BeautifulSoup
headers =  {'User-Agent': 'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0 '}

mark = ""

while mark != 'e':
    inp = input("Please enter the word to collect the data or you want to end the prosecc, enter the charcter 'e': ")
    mark = inp
    if mark == 'e':
        break
    s = requests.Session()
    url = f'https://context.reverso.net/translation/german-english/{inp}'
    web = s.get(url,headers=headers)
    soup = BeautifulSoup(web.text,"lxml")

    tag = soup.select("span",class_="text",lang="de")

    a = 1
    for i in tag:
        if ('\n' or "") in i.text :
           print(a, ". ",  i.text.strip())
           a = a+1
    # print("Do You have any List of word?")
    print("."*80)

Результат будет:

1 .  Join Reverso
2 .  
3 .  Facebook connect
4 .  Google connect
5 .  Zeigt die Anzahl der heute blockierten Ereignisse an.
6 .  Displays the number of events that have been blocked today.
7 .  In diesem Sinne werden wir heute die Entlastung verweigern.
8 .  It is for this reason that we are today refusing to grant discharge.
9 .  Die Agrarerzeugnisse sind heute ein wesentlicher Bestandteil der Verhandlungsrunden der Welthandelsorganisation.
10 .  Agricultural products are now an integral part of the World Trade Organisation negotiating round.
11 .  Das ist heute die wichtigste Frage.
12 .  This is the pressing issue we now face.
13 .  Sie wird in vergleichbaren Fällen heute anders vorgehen.
14 .  It would take a different approach in comparable cases today.
15 .  Kutschma regiert heute als allmächtiger Präsident.
16 .  Today, Kuchma rules as an all-powerful president.
17 .  Für mich verbleibt heute nur eine wesentliche Frage.
18 .  In my view, there is only one important question left today.
19 .  Die heute diskutierte Verordnung wird unsere Aktion fraglos verbessern helfen.
20 .  The regulation we are debating today will undoubtedly contribute to improving our action.


and so on......

Вы также можете попробовать:

import requests
from bs4 import BeautifulSoup
headers =  {'User-Agent': 'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0 '}

mark = ""

while mark != 'e':
    inp = input("Please enter the word to collect the data or you want to end the prosecc, enter the charcter 'e': ")
    mark = inp
    if mark == 'e':
        break
    s = requests.Session()
    url = f'https://context.reverso.net/translation/german-english/{inp}'
    web = s.get(url,headers=headers)
    soup = BeautifulSoup(web.text,"lxml")

    # tag = soup.select("span",class_="text",lang="de")

    sentences = [x.text.strip() for x in soup.find_all('span', {'class':'text'},{"lang" : "de"}) if '\n' in x.text]
    print(sentences)
    print("."*80)

Вы получите тот же результат, что и список.

...