Certainly! I'll provide a comprehensive review of your Python script, highlighting potential issues, optimizations, and best practices. Let's go through the code step by step.
1. Imports and Dependencies
import requests
import pandas as pd
import re
from datetime import date, datetime
from bs4 import BeautifulSoup
import numpy as np
import os
import pytz
Suggestions:
- Unused Imports: Ensure all imported modules are used. For instance,
re is used, but string is also referenced in remove_punctuation method without being imported.
- Order Imports: Follow PEP 8 guidelines by ordering imports: standard library, third-party libraries, then local imports, each separated by a blank line.
- Import Specifics: Instead of importing entire modules, consider importing only what's necessary to reduce memory usage and improve readability.
2. Constants and File Paths
URL = (
"https://eur-lex.europa.eu/legal-content/es/TXT/HTML/?uri=CELEX:32019D1341&from=en"
)
PEOPLE_FILE = "./list_eu/data/list_eu_people_"
ENTITIES_FILE = "./list_eu/data/list_eu_entities_"
DATA_PATH = "./list_eu/data/"
Suggestions:
-
Use os.path or pathlib: To ensure cross-platform compatibility, use os.path or pathlib for file paths.
from pathlib import Path
DATA_DIR = Path("./list_eu/data/")
PEOPLE_FILE = DATA_DIR / "list_eu_people_"
ENTITIES_FILE = DATA_DIR / "list_eu_entities_"
-
Configuration: Consider externalizing configurations like URLs and file paths, especially if they might change or if the script scales.
3. Utilities Class
The main functionality is encapsulated within the Utilities class. Let's examine its methods.
a. Initialization
class Utilities:
def __init__(self):
pass
Suggestions:
- If the class doesn't need initialization, you can make it a collection of
@staticmethods or use a different design pattern.
- If you plan to add attributes later, initializing is fine.
b. Name Validation
def name_validation(self, x):
if len(x) == 2:
return x[1].lower().strip()
elif len(x) == 3:
if (x[1][0].isupper() & ~x[1][-1].isupper()) & (
x[2][0].isupper() & ~x[2][-1].isupper()
):
return x[1].lower() + " " + x[2].lower()
else:
return x[2].lower()
Issues & Suggestions:
c. Lastname Validation
def lastname_validation(self, x):
if len(x) == 3:
if (x[0][0].isupper() & x[0][-1].isupper()) & (
x[1][0].isupper() & x[1][-1].isupper()
):
return x[0].lower() + " " + x[1].lower().strip()
else:
return x[0].lower()
else:
return x[0].lower()
Issues & Suggestions:
d. Separate Names and Lastnames
def separate_names_lastnames(self, df):
nombres = df["nombre"].tolist()
nombres = list(map(lambda x: x.split(","), nombres))
indice = 0
for i in nombres:
if len(i) < 2:
nombres[indice] = i[0].split(" ")
indice += 1
df["apellido"] = list(map(self.lastname_validation, nombres))
df["nombre_"] = list(map(self.name_validation, nombres))
df.drop(columns=["nombre"], inplace=True)
df.rename(columns={"nombre_": "nombre"}, inplace=True)
df.loc[df["pasaporte"] == "", "pasaporte"] = np.NaN
df.loc[df["identificacion"] == "", "identificacion"] = np.NaN
return df
Issues & Suggestions:
-
Variable Naming: Use English consistently unless there's a specific reason to use another language (e.g., Spanish). For example, nombres, apellido, nombre_ could be names, lastname, first_name.
-
Loop Optimization:
- Instead of using a loop with an index, consider list comprehensions.
-
Handling Empty Strings:
- Use
df.replace("", np.nan, inplace=True) for better performance.
-
Chain Methods Carefully:
- Dropping and renaming columns can be chained or handled more gracefully.
-
Example Refactor:
def separate_names_lastnames(self, df):
# Split `nombre` by comma
nombres = df["nombre"].str.split(",").apply(lambda x: x if len(x) >= 2 else x[0].split(" ")).tolist()
df["apellido"] = [self.lastname_validation(name) for name in nombres]
df["nombre_"] = [self.name_validation(name) for name in nombres]
df.drop(columns=["nombre"], inplace=True)
df.rename(columns={"nombre_": "nombre"}, inplace=True)
df.replace({"pasaporte": {"": np.nan}, "identificacion": {"": np.nan}}, inplace=True)
return df
e. Read Page
def read_page(self, soup):
tabla = soup.find(id="L_2019209ES.01001701")
personas = []
entidades = []
current_section = 'personas'
for element in tabla.find_all(['p', 'table']):
if 'II.' in element.text:
current_section = 'entidades'
continue
if element.name == 'table':
for row in element.find_all('tr'):
content = row.find_all('td')[2].text.strip()
if current_section == 'personas':
personas.append(content)
else:
entidades.append(content)
return personas, entidades
Issues & Suggestions:
f. Fill People Data
def fill_people_data(self, personas):
df = pd.DataFrame(personas, columns=['content'])
df['nombre'] = ''
df['apellido'] = ''
df['pasaporte'] = ''
df['identificacion'] = '' # Optional for future identification handling
for index, row in df.iterrows():
content = row['content']
# Step 1: Extract the full content of the <span>, remove alias part (in parentheses)
name_passport_part = re.sub(r'\(.*?\)', '', content).strip()
# Step 2: Use regex to extract surname (first uppercase word) and first name (second word)
name_match = re.match(r'([A-ZÁÉÍÓÚÜ]+)\s+([A-Z][a-záéíóúü]+)', name_passport_part)
if name_match:
df.at[index, 'apellido'] = name_match.group(1).lower() # First uppercase word as surname
df.at[index, 'nombre'] = name_match.group(2).lower() # Second word as first name
# Step 3: Extract passport number (if present)
passport_match = re.search(r'Pasaporte:\s*([A-Z0-9]+)', content)
if passport_match:
df.at[index, 'pasaporte'] = f"[{passport_match.group(1)}]"
# Step 4: Add timestamp for data processing time
df['hora_consulta'] = datetime.now(pytz.timezone("America/Bogota")).strftime(
"%Y%m%d %H %M %p"
)
return df
Issues & Suggestions:
-
Performance:
- Iterating over DataFrame rows with
iterrows() is slow for large DataFrames.
- Use vectorized operations or
df.apply where possible.
-
Regex Patterns:
- Ensure that the patterns accurately capture the intended data.
- The surname extraction assumes all uppercase letters; verify against actual data.
-
Timestamp:
- Capture the timestamp once outside the loop to ensure consistency.
-
Example Refactor:
def fill_people_data(self, personas):
df = pd.DataFrame(personas, columns=['content'])
# Remove alias parts (parentheses)
df['name_passport'] = df['content'].str.replace(r'\(.*?\)', '', regex=True).str.strip()
# Extract apellido and nombre using regex
name_pattern = r'([A-ZÁÉÍÓÚÜ]+)\s+([A-Z][a-záéíóúü]+)'
df[['apellido', 'nombre']] = df['name_passport'].str.lower().str.extract(name_pattern)
# Extract pasaporte
df['pasaporte'] = df['content'].str.extract(r'Pasaporte:\s*([A-Z0-9]+)').apply(
lambda x: f"[{x[0]}]" if pd.notnull(x[0]) else x[0], axis=1
)
# Assign NaN to empty passport and identificacion
df.replace({"pasaporte": {"": np.nan}, "identificacion": {"": np.nan}}, inplace=True)
# Timestamp
timestamp = datetime.now(pytz.timezone("America/Bogota")).strftime("%Y%m%d %H %M %p")
df['hora_consulta'] = timestamp
return df
g. Clean People Data
def clean_people_data(self, df):
df["nombre"] = df["nombre"].str.replace(r"\(", "")
df["nombre"] = df["nombre"].str.strip()
df["nombre"] = df["nombre"].str.replace(r",$", "")
df["nombre"] = df["nombre"].str.replace("-", " ")
df.drop(columns=["content"], inplace=True)
df.rename(
columns={"pasaporte": "pasaporte", "identificacion": "identificacion", "nombre": "nombre"},
inplace=True,
)
df["hora_consulta"] = datetime.now(pytz.timezone("America/Bogota")).strftime(
"%Y%m%d %H %M %p"
)
return df
Issues & Suggestions:
-
Redundant Rename:
- The
rename method is not changing anything since the column names are the same.
-
Regular Expressions:
- Use
regex=True explicitly for clarity (default in newer pandas versions).
-
Chaining Operations:
- Chain string operations to improve performance and readability.
-
Timestamp Update:
- The timestamp was already set in
fill_people_data. Updating it again may not be necessary unless intended.
-
Example Refactor:
def clean_people_data(self, df):
df["nombre"] = (
df["nombre"]
.str.replace(r"\(", "", regex=True)
.str.replace(r",$", "", regex=True)
.str.replace("-", " ", regex=False)
.str.strip()
)
df.drop(columns=["content"], inplace=True)
# If hora_consulta needs to be updated, otherwise remove this line
df["hora_consulta"] = datetime.now(pytz.timezone("America/Bogota")).strftime(
"%Y%m%d %H %M %p"
)
return df
h. Fill Entities Data
def fill_entities_data(self, entidades):
entidades = list(
map(
lambda x: self.normalize(x)
.replace("-", " ")
.replace(" – ", " ")
.replace("\xa0", " ")
.replace(".", "")
.replace("/", " "),
entidades,
)
)
df = pd.DataFrame(entidades)
df["col1"] = ""
entidad = re.compile(r'«(.+?)»')
for index, row in df.iterrows():
match = entidad.search(row[0].lower())
if match:
row["col1"] = match.group(1)
entidad = re.compile(r'\d+\.\s*(.+)')
for index, row in df.iterrows():
if row["col1"] == "":
match = entidad.search(row[0].lower())
if match:
row["col1"] = match.group(1)
df.drop(columns=[0], inplace=True)
df.rename(columns={"col1": "nombre"}, inplace=True)
df["hora_consulta"] = datetime.now(pytz.timezone("America/Bogota")).strftime(
"%Y%m%d %H %M %p"
)
return df
Issues & Suggestions:
-
Performance:
- Similar to earlier, avoid using
iterrows(). Use vectorized operations or df.apply.
-
Regex Logic:
- Ensure that the regex accurately captures the intended entities.
- There’s a two-step matching process; consider combining it if possible.
-
Column Naming:
- Initially, the DataFrame has a single column with default name
0. Renaming it later can be streamlined.
-
Handling Unicode and Special Characters:
- Ensure that cleaning steps handle all cases needed.
-
Example Refactor:
def fill_entities_data(self, entidades):
# Normalize and replace characters
entidades = [
self.normalize(x)
.replace("-", " ")
.replace(" – ", " ")
.replace("\xa0", " ")
.replace(".", "")
.replace("/", " ")
for x in entidades
]
df = pd.DataFrame({'raw': entidades})
df['lower_raw'] = df['raw'].str.lower()
# Extract entities within «»
df['nombre'] = df['lower_raw'].str.extract(r'«(.+?)»')
# For rows without «», extract after numbering
df['nombre'] = df.apply(
lambda row: row['nombre'] if pd.notnull(row['nombre']) else re.search(r'\d+\.\s*(.+)', row['lower_raw']).group(1) if re.search(r'\d+\.\s*(.+)', row['lower_raw']) else np.nan,
axis=1
)
# Drop intermediate columns
df.drop(columns=['raw', 'lower_raw'], inplace=True)
# Timestamp
timestamp = datetime.now(pytz.timezone("America/Bogota")).strftime("%Y%m%d %H %M %p")
df['hora_consulta'] = timestamp
return df
Alternatively, using fillna and chain operations:
def fill_entities_data(self, entidades):
entidades = [
self.normalize(x)
.replace("-", " ")
.replace(" – ", " ")
.replace("\xa0", " ")
.replace(".", "")
.replace("/", " ")
for x in entidades
]
df = pd.DataFrame({'raw': entidades})
df['lower_raw'] = df['raw'].str.lower()
# Extract entities within «»
df['nombre'] = df['lower_raw'].str.extract(r'«(.+?)»')
# Extract after numbering if 'nombre' is NaN
df['nombre'] = df['nombre'].fillna(df['lower_raw'].str.extract(r'\d+\.\s*(.+)')[0])
# Drop intermediate columns
df.drop(columns=['raw', 'lower_raw'], inplace=True)
# Timestamp
timestamp = datetime.now(pytz.timezone("America/Bogota")).strftime("%Y%m%d %H %M %p")
df['hora_consulta'] = timestamp
return df
i. Normalize
def normalize(self, s):
replacements = (
("á", "a"),
("é", "e"),
("í", "i"),
("ó", "o"),
("ú", "u"),
("ü", "u"),
)
for a, b in replacements:
s = s.replace(a, b).replace(a.upper(), b.upper())
return s
Suggestions:
-
Performance:
- Consider using
str.translate or regular expressions for multiple replacements.
-
Unicode Normalization:
- Alternatively, use
unicodedata to normalize strings, which might cover more cases.
-
Example Using str.translate:
import unicodedata
def normalize(self, s):
return ''.join(
(c.lower().replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('ü', 'u') if c.lower() in 'áéíóúü'
else c)
for c in s
)
Or using unicodedata:
import unicodedata
def normalize(self, s):
normalized = unicodedata.normalize('NFD', s)
return ''.join(c for c in normalized if unicodedata.category(c) != 'Mn').replace('ü', 'u').replace('Ü', 'U')
j. Remove Punctuation
def remove_punctuation(self, text):
return re.sub("[%s]" % re.escape(string.punctuation), "", text)
Issues & Suggestions:
-
Missing Import:
string is not imported. Add import string at the top.
-
Performance:
- Use
str.translate for faster punctuation removal.
-
Example Refactor:
import string
def remove_punctuation(self, text):
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator)
k. Get Data EU List
def get_data_eu_list(self):
req = requests.get(URL)
soup = BeautifulSoup(req.content, "html.parser")
personas, entidades = self.read_page(soup)
print('Sitio de terroristas de la Unión Europea leído correctamente')
df_personas = self.fill_people_data(personas)
df_personas = self.clean_people_data(df_personas)
df_personas = self.separate_names_lastnames(df_personas)
df_entidades = self.fill_entities_data(entidades)
df_personas = df_personas[['pasaporte', 'identificacion', 'hora_consulta', 'apellido', 'nombre']]
return df_personas.to_csv(
PEOPLE_FILE + date.today().strftime("%d%m%Y") + ".csv",
sep=";",
index=False,
), df_entidades.to_csv(
ENTITIES_FILE
+ date.today().strftime("%d%m%Y")
+ ".csv",
sep=";",
index=False,
)
Issues & Suggestions:
-
Error Handling:
-
Logging:
- Instead of
print, consider using the logging module for better control over log levels and outputs.
-
Date Formatting:
- Use
strftime once and reuse the formatted date to prevent discrepancies between filenames.
-
Return Values:
- The method returns a tuple of CSV strings. If the intention is to save files, perhaps return the file paths or acknowledgment.
-
Example Refactor:
import logging
def get_data_eu_list(self):
logging.info("Starting data retrieval from EU list.")
try:
req = requests.get(URL)
req.raise_for_status()
except requests.RequestException as e:
logging.error(f"Error fetching URL: {e}")
return None
soup = BeautifulSoup(req.content, "html.parser")
try:
personas, entidades = self.read_page(soup)
logging.info('EU terrorist site read successfully.')
except Exception as e:
logging.error(f"Error parsing page: {e}")
return None
df_personas = self.fill_people_data(personas)
df_personas = self.clean_people_data(df_personas)
df_personas = self.separate_names_lastnames(df_personas)
df_entidades = self.fill_entities_data(entidades)
# Select required columns
df_personas = df_personas[['pasaporte', 'identificacion', 'hora_consulta', 'apellido', 'nombre']]
# Format date once
today_str = date.today().strftime("%d%m%Y")
people_file_path = f"{PEOPLE_FILE}{today_str}.csv"
entities_file_path = f"{ENTITIES_FILE}{today_str}.csv"
# Save to CSV
df_personas.to_csv(people_file_path, sep=";", index=False)
df_entidades.to_csv(entities_file_path, sep=";", index=False)
logging.info(f"Data saved to {people_file_path} and {entities_file_path}.")
return people_file_path, entities_file_path
l. Read Data
def read_data(self):
data_files = os.listdir(DATA_PATH)
files_people = []
files_entities = []
for i in data_files:
if "list_eu_people" in i:
files_people.append(datetime.strptime(i[15:-4], "%d%m%Y").date())
elif "list_eu_entities" in i:
files_entities.append(datetime.strptime(i[17:-4], "%d%m%Y").date())
return pd.read_csv(
PEOPLE_FILE
+ max(files_people).strftime("%d%m%Y")
+ ".csv",
sep=";",
), pd.read_csv(
ENTITIES_FILE
+ max(files_entities).strftime("%d%m%Y")
+ ".csv",
sep=";",
)
Issues & Suggestions:
-
Error Handling:
-
File Parsing:
-
The slicing (i[15:-4] and i[17:-4]) assumes fixed filename lengths. This can break if filenames change.
-
Use regex or string methods to extract dates more reliably.
import re
for filename in data_files:
people_match = re.match(r'list_eu_people_(\d{8})\.csv', filename)
if people_match:
date_str = people_match.group(1)
files_people.append(datetime.strptime(date_str, "%d%m%Y").date())
continue
entities_match = re.match(r'list_eu_entities_(\d{8})\.csv', filename)
if entities_match:
date_str = entities_match.group(1)
files_entities.append(datetime.strptime(date_str, "%d%m%Y").date())
-
Code Duplication:
- Reading the latest file for both people and entities can be abstracted into a helper method.
-
Example Refactor:
import re
def read_data(self):
data_files = os.listdir(DATA_PATH)
files_people = []
files_entities = []
date_pattern_people = re.compile(r'list_eu_people_(\d{8})\.csv')
date_pattern_entities = re.compile(r'list_eu_entities_(\d{8})\.csv')
for filename in data_files:
people_match = date_pattern_people.match(filename)
if people_match:
date_str = people_match.group(1)
files_people.append(datetime.strptime(date_str, "%d%m%Y").date())
continue
entities_match = date_pattern_entities.match(filename)
if entities_match:
date_str = entities_match.group(1)
files_entities.append(datetime.strptime(date_str, "%d%m%Y").date())
if not files_people:
raise ValueError("No people data files found.")
if not files_entities:
raise ValueError("No entities data files found.")
latest_people_date = max(files_people)
latest_entities_date = max(files_entities)
people_file = f"{PEOPLE_FILE}{latest_people_date.strftime('%d%m%Y')}.csv"
entities_file = f"{ENTITIES_FILE}{latest_entities_date.strftime('%d%m%Y')}.csv"
if not Path(people_file).exists() or not Path(entities_file).exists():
raise FileNotFoundError("Latest data files not found.")
df_people = pd.read_csv(people_file, sep=";")
df_entities = pd.read_csv(entities_file, sep=";")
return df_people, df_entities
4. Main Execution Block
if __name__ == "__main__":
utl = Utilities()
utl.get_data_eu_list()
Suggestions:
-
Main Function:
- Encapsulate the main execution logic within a
main function for better structure.
-
Logging Setup:
- Initialize logging within the main block.
-
Example Refactor:
import logging
def main():
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
utl = Utilities()
try:
people_file, entities_file = utl.get_data_eu_list()
logging.info(f"Data successfully saved to {people_file} and {entities_file}.")
except Exception as e:
logging.error(f"An error occurred: {e}")
if __name__ == "__main__":
main()
5. Additional Best Practices
-
Documentation:
- Add docstrings to classes and methods to explain their purpose, parameters, and return values.
-
Type Hints:
-
Incorporate type hints for better readability and to aid tools like linters and IDEs.
def normalize(self, s: str) -> str:
...
-
Unit Tests:
- Develop unit tests for critical functions to ensure reliability and facilitate future changes.
-
Exception Handling:
- Implement robust exception handling to catch and respond to unexpected issues gracefully.
-
Virtual Environment:
- Use a virtual environment to manage dependencies, ensuring consistency across different setups.
-
Requirements File:
6. Final Thoughts
Your script is well-structured and demonstrates a clear approach to scraping and processing data from the EU website. By addressing the points mentioned above, you can enhance its robustness, readability, and maintainability. Implementing these changes will also make troubleshooting easier and pave the way for future enhancements.
Feel free to ask if you have specific questions or need further assistance with any part of the code!