2017-05-20 2 views
2

Ich versuche, jedes Stück individuellen Text zwischen jedem Tag (das ist in meiner Liste) in einer TXT-Datei mit schönen Suppe und speichern Sie sie in ein Wörterbuch. Dieser Code funktioniert, ist aber schrecklich langsam, wenn ich große Dateien starte. Gibt es also eine andere Möglichkeit, diesen Code schneller zu machen?Greifen Sie den Text zwischen den Tags mit BeautifulSoup

from bs4 import BeautifulSoup 

words_dict = dict() 

# these are all of the tags in the file I'm looking for 
tags_list = ['title', 'h1', 'h2', 'h3', 'b', 'strong'] 

def grab_file_content(file : str): 
    with open(file, encoding = "utf-8") as file_object: 
     # entire content of the file with tags 
     content = BeautifulSoup(file_object, 'html.parser') 

     # if the content has content within the <body> tags... 
     if content.body: 
      for tag in tags_list: 
       for tags in content.find_all(tag): 
        text_list = tags.get_text().strip().split(" ") 
        for words in text_list: 
         if words in words_dict: 
          words_dict[words] += 1 
         else: 
          words_dict[words] = 1 

     else: 
      print('no body') 
+0

Sie sagen, Sie Text _between_ Die Tags werden soll (die zwischen, sagen wir,

und andere

wäre), aber in Ihrem Beispielsweise extrahieren Sie Wörter _within_ the tags (nämlich zwischen dem und dem). Was willst du? – DyZ

+0

Ah ja, ich möchte die Eingabe in der Mitte der beiden Tags. So zum Beispiel

Mein Text

, ich möchte, dass mein Wörterbuch {My: 1, Text: 1} speichert. Dank dafür – dppham1

Antwort

1

Der folgende Code ist funktional äquivalent zu Ihren Code:

from collections import Counter  
from itertools import chain 

words_dict = Counter() # An empty counter further used as an accumulator 

# Probably a loop 
# Create the soup here, as in your original code 
content = BeautifulSoup(file_object, 'html.parser') 
words_dict += Counter(chain.from_iterable(tag.string.split() 
         for tag in content.find_all(tags_list) if tag.string)) 
Verwandte Themen