2016-04-27 5 views
0

Ich wollte eine Datenbank mit häufig verwendeten Wörtern erstellen. Gerade jetzt, wenn ich dieses Skript ausführe funktioniert es gut, aber mein größtes Problem ist, ich brauche alle Wörter in einer Spalte. Ich habe das Gefühl, dass das, was ich getan habe, mehr ein Hack als eine echte Reparatur war. Mit Beautifulsoup, können Sie alles in einer Spalte ohne zusätzliche Leerzeilen drucken?Python Web Scraper mit Beautifulsoup 4

import requests 
import re 
from bs4 import BeautifulSoup 

#Website you want to scrap info from 
res = requests.get("https://github.com/first20hours/google-10000-english/blob/master/google-10000-english-usa.txt") 
# Getting just the content using bs4 
soup = BeautifulSoup(res.content, "lxml") 

# Creating the CSV file 
commonFile = open('common_words.csv', 'wb') 

# Grabbing the lines you want 
    for node in soup.findAll("tr"): 
    # Getting just the text and removing the html 
    words = ''.join(node.findAll(text=True)) 
    # Removing the extra lines 
    ID = re.sub(r'[\t\r\n]', '', words) 
    # Needed to add a break in the line to make the rows 
    update = ''.join(ID)+'\n' 
    # Now we add this to the file 
    commonFile.write(update) 
commonFile.close() 

Antwort

1

Wie wäre es damit?

import requests 
import csv 
from bs4 import BeautifulSoup 

f = csv.writer(open("common_words.csv", "w")) 
f.writerow(["common_words"]) 

#Website you want to scrap info from 
res = requests.get("https://github.com/first20hours/google-10000-english/blob/master/google-10000-english-usa.txt") 
# Getting just the content using bs4 
soup = BeautifulSoup(res.content, "lxml") 

words = soup.select('div[class=file] tr') 

for i in range(len(words)): 
    word = words[i].text 
    f.writerow([word.replace('\n', '')])