# Install necessary libraries
!pip install requests beautifulsoup4 spacy
!python -m spacy download en_core_web_sm
import requests
from bs4 import BeautifulSoup
import spacy
import re
from urllib.parse import urljoin
# Load English language model for spaCy
nlp = spacy.load("en_core_web_sm")
def get_wikipedia_content(url):
"""Fetch content from Wikipedia article"""
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"Error fetching URL: {e}")
return None
def extract_text_from_html(html_content):
"""Extract text content from HTML"""
soup = BeautifulSoup(html_content, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get main content
content = soup.find('div', class_='mw-parser-output')
if content:
# Get text
text = content.get_text()
# Break into lines and remove leading/trailing space
lines = (line.strip() for line in text.splitlines())
# Break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
# Drop blank lines
text = ' '.join(chunk for chunk in chunks if chunk)
return text
return ""
def extract_names(text):
"""Extract potential names using spaCy"""
# Process text with spaCy
doc = nlp(text)
# Extract person names
names = set()
for ent in doc.ents:
if ent.label_ == "PERSON":
# Clean the name
name = ent.text.strip()
# Basic validation to filter out obvious non-names
if re.match(r'^[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*$', name):
names.add(name)
return sorted(list(names))
def main():
url = "https://en.wikipedia.org/wiki/Donald_Trump"
print(f"Fetching content from: {url}")
# Get HTML content
html_content = get_wikipedia_content(url)
if not html_content:
return
# Extract text
text_content = extract_text_from_html(html_content)
if not text_content:
print("Could not extract content from the page")
return
# Extract names
print("\nExtracting potential names...")
names = extract_names(text_content)
# Print results
print(f"\nFound {len(names)} potential names:")
for i, name in enumerate(names, 1):
print(f"{i}. {name}")
if __name__ == "__main__":
main()
Key changes for Google Colab:
Installation within Colab: I've added !pip install and !python -m spacy download commands at the beginning. The ! prefix tells Colab to execute these as shell commands. This installs the necessary libraries directly in the Colab environment.
No local file paths: The code doesn't rely on any local files, making it directly runnable in Colab.
This revised code should run without issues in a Google Colab notebook. Just copy and paste it into a code cell and execute it. The output will be printed directly in the Colab notebook. Be aware that the first time you run it, it will take a bit longer because it needs to download and install the libraries.
User
try again im running on google collab
Assistant
python
# Install necessary libraries (only needed once per Colab session)
!pip install requests beautifulsoup4 spacy
!python -m spacy download en_core_web_sm
import requests
from bs4 import BeautifulSoup
import spacy
import re
from urllib.parse import urljoin
# Load English language model for spaCy
nlp = spacy.load("en_core_web_sm")
def get_wikipedia_content(url):
"""Fetch content from Wikipedia article"""
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"Error fetching URL: {e}")
return None
def extract_text_from_html(html_content):
"""Extract text content from HTML"""
soup = BeautifulSoup(html_content, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get main content
content = soup.find('div', class_='mw-parser-output')
if content:
# Get text
text = content.get_text()
# Break into lines and remove leading/trailing space
lines = (line.strip() for line in text.splitlines())
# Break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
# Drop blank lines
text = ' '.join(chunk for chunk in chunks if chunk)
return text
return ""
def extract_names(text):
"""Extract potential names using spaCy"""
# Process text with spaCy
doc = nlp(text)
# Extract person names
names = set()
for ent in doc.ents:
if ent.label_ == "PERSON":
# Clean the name
name = ent.text.strip()
# Basic validation to filter out obvious non-names
if re.match(r'^[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*$', name):
names.add(name)
return sorted(list(names))
def main():
url = "https://en.wikipedia.org/wiki/Donald_Trump"
print(f"Fetching content from: {url}")
# Get HTML content
html_content = get_wikipedia_content(url)
if not html_content:
return
# Extract text
text_content = extract_text_from_html(html_content)
if not text_content:
print("Could not extract content from the page")
return
# Extract names
print("\nExtracting potential names...")
names = extract_names(text_content)
# Print results
print(f"\nFound {len(names)} potential names:")
for i, name in enumerate(names, 1):
print(f"{i}. {name}")
if __name__ == "__main__":
main()
Key changes for Google Colab:
Installation within Colab: I've added !pip install and !python -m spacy download commands at the beginning. The ! tells Colab to execute the command in the shell. These commands install the necessary libraries and download the spaCy language model. You only need to run these cells once per Colab session.
No file path issues: Colab doesn't have the same file system concerns as a local machine, so there are no issues with loading the spaCy model.
Direct execution: The code is designed to run directly in a Colab notebook cell.
Copy and paste the code: Copy the entire code block above and paste it into a code cell in your Colab notebook.
Run the installation cells: Run the first two cells (the ones with !pip install and !python -m spacy download). This might take a few minutes.
Run the main code cell: Run the remaining code cell. The script will fetch the Wikipedia article, extract the text, identify potential names, and print them to the Colab output.
The output will be a numbered list of potential names found in the article. As mentioned before, the results may not be perfect, but this provides a good starting point.