Создание нескольких текстовых файлов с уникальными именами файлов из очищенных данных - PullRequest
0 голосов
/ 16 января 2020

Я прошел вводный курс в Python в этом семестре и сейчас пытаюсь сделать проект. Однако я не знаю, какой код мне следует написать, чтобы создать несколько файлов .txt, заголовок которых будет отличаться для каждого файла.

Я удалил все термины и определения с веб-сайта http://www.hogwartsishere.com/library/book/99/. Например, заголовок файла .txt должен быть «Aconite.txt», а содержимое файла - заголовком и определением. Каждый термин с его определением можно найти в отдельном p-теге, а сам термин является b-тегом с p-тегом. Могу ли я использовать это для написания своего кода?

Полагаю, для этого мне понадобится for-l oop, но я не знаю, с чего начать. Я искал StackOverflow и нашел несколько решений, но все они содержат код, с которым я не знаком и / или не связан с другой проблемой.

Вот что у меня есть:

#!/usr/bin/env/ python

import requests
import bs4

def download(url):
    r = requests.get(url) 
    html = r.text
    soup = bs4.BeautifulSoup(html, 'html.parser')
    terms_definition = []

    #for item in soup.find_all('p'): #beter definiëren
    items = soup.find_all("div", {"class" : "font-size-16 roboto"})
    for item in items:
        terms = item.find_all("p")
        for term in terms:
            #print(term)
            if term.text is not 'None':
                #print(term.text)
                #print("\n")
                term_split = term.text.split()
                print(term_split)

            if term.text != None and len(term.text) > 1:
                if '-' in term.text.split():
                    print(term.text)
                    print('\n')
                if item.find('p'):
                    terms_definition.append(item['p'])
                print(terms_definition)

    return terms_definition

def create_url(start, end):
    list_url = []
    base_url = 'http://www.hogwartsishere.com/library/book/99/chapter/'
    for x in range(start, end):
        list_url.append(base_url + str(x))

    return list_url

def search_all_url(list_url):
    for url in list_url:
        download(url)

#write data into separate text files. Word in front of the dash should be title of the document, term and definition should be content of the text file
#all terms and definitions are in separate p-tags, title is a b-tag within the p-tag
def name_term



def text_files
    path_write = os.path.join('data', name_term +'.txt') #'term' should be replaced by the scraped terms

    with open(path_write, 'w') as f:
    f.write()
#for loop? in front of dash = title / everything before and after dash = text (file content) / empty line = new file



if __name__ == '__main__':
    download('http://www.hogwartsishere.com/library/book/99/chapter/1')
    #list_url = create_url(1, 27)
    #search_all_url(list_url)

Заранее спасибо!

1 Ответ

0 голосов
/ 16 января 2020

Вы можете перебрать все страницы (1-27), чтобы получить его содержимое, затем проанализировать каждую страницу с помощью bs4 и затем сохранить результаты в файлы:

import requests
import bs4
import re

for i in range(1, 27):
    r = requests.get('http://www.hogwartsishere.com/library/book/99/chapter/{}/'.format(i)).text
    soup = bs4.BeautifulSoup(r, 'html.parser')
    items = soup.find_all("div", {"class": "font-size-16 roboto"})
    for item in items:
        terms = item.find_all("p")
        for term in terms:
            title = re.match('^(.*) -', term.text).group(1).replace('/', '-')
            with open(title + '.txt', 'w', encoding='utf-8') as f:
                f.write(term.text)

Выходные файлы:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...