how to detect personal data like name , email,phone number, ssn, credit card no in csv…
- User
how to detect personal data like name , email,phone number, ssn, credit card no in csv data using python
- Assistant
how to detect personal data like name , email,phone number, ssn, credit card no in csv data using python
Detecting personal data such as names, emails, phone numbers, Social Security Numbers (SSNs), and credit card numbers in CSV data using Python can be accomplished using several libraries and techniques. Here's a comprehensive guide to achieve this:
You'll need a few libraries such as pandas for handling CSV data, re for regular expressions, and potentially phonenumbers for phone number validation.
pip install pandas phonenumbers
import pandas as pd
import re
import phonenumbers
You can use regular expressions to detect emails, SSNs, and credit card numbers. For phone numbers, you can use the phonenumbers library.
def detect_email(text):
email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')
return email_pattern.findall(text)
def detect_phone_number(text):
phone_numbers = []
for match in phonenumbers.PhoneNumberMatcher(text, "US"):
phone_numbers.append(phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL))
return phone_numbers
def detect_ssn(text):
ssn_pattern = re.compile(r'\b\d{3}-\d{2}-\d{4}\b')
return ssn_pattern.findall(text)
def detect_credit_card(text):
# This is a very simplistic approach and may not be fully exhaustive
cc_pattern = re.compile(r'\b(?:\d[ -]*?){13,16}\b')
return cc_pattern.findall(text)
def load_csv(filepath):
return pd.read_csv(filepath)
Go through each cell in each column to detect personal data.
def detect_personal_data(df):
personal_data = []
for column in df.columns:
for index, value in df[column].items():
value = str(value)
emails = detect_email(value)
phones = detect_phone_number(value)
ssns = detect_ssn(value)
credit_cards = detect_credit_card(value)
if emails or phones or ssns or credit_cards:
personal_data.append({
'row': index,
'column': column,
'emails': emails,
'phones': phones,
'ssns': ssns,
'credit_cards': credit_cards
})
return personal_data
if __name__ == "__main__":
# Load your CSV file
filepath = 'your_file.csv'
df = load_csv(filepath)
# Detect personal data
results = detect_personal_data(df)
# Output the detected personal data
for result in results:
print(result)
pandas, phonenumbers.phonenumbers library.pandas.Please note that the regular expressions for SSNs and credit cards are simplified and may not cover all edge cases. For production-level code, more sophisticated validation and parsing may be necessary.
Not yet included in a published release.