Решение на Регулярни изрази от Антон Стоянов

Обратно към всички решения

Към профила на Антон Стоянов

Резултати

  • 2 точки от тестове
  • 0 бонус точки
  • 2 точки общо
  • 6 успешни тест(а)
  • 33 неуспешни тест(а)

Код

import re
import datetime
import time
MAIL_PATTERN = "[a-zA-Z0-9][\w\+\.\-]{1,200}"
DOMAIN_PATTERN = "([a-zA-Z0-9][a-zA-Z0-9\-]{1,61}[a-zA-Z0-9]\.)+"
TLD_PATTERN = "([a-zA-Z]{2,3})(\.[a-zA-Z]{2,3})?"
PHONE_PREFIX_PATTERN = "(0|00|\+)[1-9]\d{0,2}"
PHONE_MAIN_PATTERN = "(\d[ \-\(\)]{0,2}){6,10}\d"
class PrivacyFilter():
def __init__(self, text):
self.__text_to_be_filtered = text
self.preserve_phone_country_code = False
self.preserve_email_hostname = False
self.partially_preserve_email_username = False
def __replace_mail_partially(self, match_text):
whole_mail = match_text.group()
username = re.match(MAIL_PATTERN+'@', whole_mail).group()
return re.sub(username, username[0:3]+"[FILTERED]@", whole_mail)
def __replace_whole_username(self, match_text):
return re.sub(MAIL_PATTERN+'@', "[FILTERED]@", match_text.group())
def __replace_phone_main_part(self, phone):
prefix = re.match(PHONE_PREFIX_PATTERN, phone.group()).group()
return prefix+' [FILTERED]'
def filtered(self):
replaced = self.__text_to_be_filtered[:]
mail = re.compile(MAIL_PATTERN + '@' + DOMAIN_PATTERN + TLD_PATTERN)
phone = re.compile(PHONE_PREFIX_PATTERN + PHONE_MAIN_PATTERN)
email_matches = re.findall(mail, replaced)
if email_matches:
if self.partially_preserve_email_username:
replaced = re.sub(mail, self.__replace_mail_partially, replaced)
elif self.preserve_email_hostname:
replaced = re.sub(mail, self.__replace_whole_username, replaced)
else:
replaced = re.sub(mail, "[EMAIL]", replaced)
phone_matches = re.findall(phone, replaced)
if phone_matches:
if self.preserve_phone_country_code:
replaced = re.sub(phone, self.__replace_phone_main_part, replaced)
else:
replaced = re.sub(phone, "[PHONE]", replaced)
return replaced
class Validations:
@classmethod
def is_email(cls, mail):
mail_pattern = re.compile(MAIL_PATTERN)
splitted = re.split("@", mail)
if len(splitted) > 2:
return False
return (mail_pattern.fullmatch(splitted[0]) is not None
and cls.is_hostname(splitted[1]))
@classmethod
def is_phone(cls, phone):
phone_regex = re.compile(PHONE_PREFIX_PATTERN + PHONE_MAIN_PATTERN)
return re.fullmatch(phone_regex, phone) is not None
@classmethod
def is_hostname(cls, hostname):
TLD = TLD_PATTERN
domain = DOMAIN_PATTERN
return re.fullmatch(domain+TLD, hostname) is not None
@classmethod
def is_ip_address(cls, ip):
pattern = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
if pattern.fullmatch(ip) is None:
return False
split_ip = re.split('\.', ip)
for number in split_ip:
number = int(number)
if number > 255 or number < 0:
return False
return True
@classmethod
def is_number(cls, value):
pattern = re.compile("-?(0|[1-9]\d*)(\.\d+)?")
return pattern.fullmatch(value) is not None
return False
@classmethod
def is_integer(cls, value):
pattern = re.compile("-?(0|[1-9]\d*)")
return pattern.fullmatch(value) is not None
@classmethod
def is_date(cls, date_to_check):
date_pattern = re.compile("\d{4}-\d{2}-\d{2}")
if date_pattern.fullmatch(date_to_check) is None:
return False
try:
datetime.datetime.strptime(date_to_check,"%Y-%m-%d")
except:
return False
return True
@classmethod
def is_time(cls, time_to_check):
time_pattern = re.compile("\d{2}:\d{2}:\d{2}")
if time_pattern.fullmatch(time_to_check) is None:
return False
try:
time.strptime(time_to_check,"%H:%M:%S")
except:
return False
return True
@classmethod
def is_datetime(cls, date_time):
delimiter = re.compile("[ ]+|T+")
splitted = delimiter.split(date_time)
return cls.is_date(splitted[0]) and cls.is_time(splitted[1])

Лог от изпълнението

..FFFFFF....EEEEEEEEEEEEEEEEEEEEEEEEEEE
======================================================================
ERROR: test_allows_huge_years_in_date_validation (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 246, in test_allows_huge_years_in_date_validation
    self.assertTrue(solution.Validations.is_date('9999-01-01'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_allows_validation_for_emails (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 105, in test_allows_validation_for_emails
    self.assertTrue(solution.Validations.is_email('foo@bar.com'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 65, in is_email
    return (mail_pattern.fullmatch(splitted[0]) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_allows_zero_years_in_date_validation (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 243, in test_allows_zero_years_in_date_validation
    self.assertTrue(solution.Validations.is_date('0000-01-01'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_can_validate_more_complex_emails (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 124, in test_can_validate_more_complex_emails
    self.assertIs(solution.Validations.is_email(email), valid)
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 65, in is_email
    return (mail_pattern.fullmatch(splitted[0]) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_can_validate_more_complex_phone_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 160, in test_can_validate_more_complex_phone_numbers
    self.assertIs(solution.Validations.is_phone(phone), valid)
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 71, in is_phone
    return re.fullmatch(phone_regex, phone) is not None
AttributeError: 'module' object has no attribute 'fullmatch'

======================================================================
ERROR: test_does_not_allow_invalid_hours_minutes_or_seconds (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 270, in test_does_not_allow_invalid_hours_minutes_or_seconds
    self.assertFalse(solution.Validations.is_time('24:00:00'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 120, in is_time
    if time_pattern.fullmatch(time_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_does_not_allow_invalid_months_or_days_in_dates (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 254, in test_does_not_allow_invalid_months_or_days_in_dates
    self.assertFalse(solution.Validations.is_date('2012-13-01'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_does_not_allow_zero_months_or_days_in_dates (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 249, in test_does_not_allow_zero_months_or_days_in_dates
    self.assertFalse(solution.Validations.is_date('1000-00-01'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_does_not_break_on_emails_in_multiline_strings (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 127, in test_does_not_break_on_emails_in_multiline_strings
    self.assertFalse(solution.Validations.is_email("foo@bar.com\nwat?"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 65, in is_email
    return (mail_pattern.fullmatch(splitted[0]) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_does_not_break_on_phones_in_multiline_strings (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 163, in test_does_not_break_on_phones_in_multiline_strings
    self.assertFalse(solution.Validations.is_phone("0885123123\nwat?"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 71, in is_phone
    return re.fullmatch(phone_regex, phone) is not None
AttributeError: 'module' object has no attribute 'fullmatch'

======================================================================
ERROR: test_handles_multiline_strings_in_IP_validation_properly (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 189, in test_handles_multiline_strings_in_IP_validation_properly
    self.assertFalse(solution.Validations.is_ip_address("8.8.8.8\n"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 82, in is_ip_address
    if pattern.fullmatch(ip) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_handles_multiline_strings_in_hostname_validation_properly (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 179, in test_handles_multiline_strings_in_hostname_validation_properly
    self.assertFalse(solution.Validations.is_hostname("foo.com\n"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 77, in is_hostname
    return re.fullmatch(domain+TLD, hostname) is not None
AttributeError: 'module' object has no attribute 'fullmatch'

======================================================================
ERROR: test_handles_multiline_strings_in_integer_validation_properly (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 233, in test_handles_multiline_strings_in_integer_validation_properly
    self.assertFalse(solution.Validations.is_number("42\n24"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 96, in is_number
    return pattern.fullmatch(value) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_handles_multiline_strings_in_numbers_validation_properly (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 215, in test_handles_multiline_strings_in_numbers_validation_properly
    self.assertFalse(solution.Validations.is_number("42\n24"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 96, in is_number
    return pattern.fullmatch(value) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_handles_newlines_in_date_validation (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 259, in test_handles_newlines_in_date_validation
    self.assertFalse(solution.Validations.is_date("2012-11-19\n"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_handles_newlines_in_time_and_datetime_validation (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 288, in test_handles_newlines_in_time_and_datetime_validation
    self.assertFalse(solution.Validations.is_time("12:01:01\n"))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 120, in is_time
    if time_pattern.fullmatch(time_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_returns_boolean_True_or_False (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 109, in test_returns_boolean_True_or_False
    self.assertIs(solution.Validations.is_email('foo@bar.com'), True)
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 65, in is_email
    return (mail_pattern.fullmatch(splitted[0]) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_IP_addresses (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 183, in test_validates_IP_addresses
    self.assertTrue(solution.Validations.is_ip_address('1.2.3.4'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 82, in is_ip_address
    if pattern.fullmatch(ip) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_dates (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 237, in test_validates_dates
    self.assertTrue(solution.Validations.is_date('2012-11-19'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_datetime_values (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 277, in test_validates_datetime_values
    self.assertTrue(solution.Validations.is_datetime('2012-11-19 19:00:00'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 134, in is_datetime
    return cls.is_date(splitted[0]) and cls.is_time(splitted[1])
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 107, in is_date
    if date_pattern.fullmatch(date_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_hostnames (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 166, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('domain.tld'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 77, in is_hostname
    return re.fullmatch(domain+TLD, hostname) is not None
AttributeError: 'module' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_integers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 219, in test_validates_integers
    self.assertTrue(solution.Validations.is_integer('42'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 102, in is_integer
    return pattern.fullmatch(value) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_more_complex_integers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 223, in test_validates_more_complex_integers
    self.assertFalse(solution.Validations.is_integer(' 42 '))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 102, in is_integer
    return pattern.fullmatch(value) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_more_complex_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 200, in test_validates_more_complex_numbers
    self.assertFalse(solution.Validations.is_number(' 42 '))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 96, in is_number
    return pattern.fullmatch(value) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 194, in test_validates_numbers
    self.assertTrue(solution.Validations.is_number('42'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 96, in is_number
    return pattern.fullmatch(value) is not None
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_phone_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 130, in test_validates_phone_numbers
    self.assertTrue(solution.Validations.is_phone('+35929555111'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 71, in is_phone
    return re.fullmatch(phone_regex, phone) is not None
AttributeError: 'module' object has no attribute 'fullmatch'

======================================================================
ERROR: test_validates_times (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 263, in test_validates_times
    self.assertTrue(solution.Validations.is_time('12:00:00'))
  File "/tmp/d20140513-11348-17j1yn5/solution.py", line 120, in is_time
    if time_pattern.fullmatch(time_to_check) is None:
AttributeError: '_sre.SRE_Pattern' object has no attribute 'fullmatch'

======================================================================
FAIL: test_does_not_brake_with_unicode (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 64, in test_does_not_brake_with_unicode
    self.assertEqual('За връзка: [FILTERED]@example.com', self.partially_filter_email_usernames('За връзка: me@example.com'))
AssertionError: 'За връзка: [FILTERED]@example.com' != 'За връзка: me@[FILTERED]@example.com'
- За връзка: [FILTERED]@example.com
+ За връзка: me@[FILTERED]@example.com
?            +++


======================================================================
FAIL: test_does_not_filter_invalid_emails (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 48, in test_does_not_filter_invalid_emails
    self.assertEqual(text, solution.PrivacyFilter(text).filtered())
AssertionError: 'Contact me here: _invalid@email.com' != 'Contact me here: _[EMAIL]'
- Contact me here: _invalid@email.com
+ Contact me here: _[EMAIL]


======================================================================
FAIL: test_does_not_filter_invalid_phone_numbers (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '0005551234569' != '0[PHONE]'
- 0005551234569
+ 0[PHONE]


======================================================================
FAIL: test_filters_more_complex_phone_numbers (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[PHONE]' != '+1 (555) 123-456-99'
- [PHONE]
+ +1 (555) 123-456-99


======================================================================
FAIL: test_filters_whole_email_usernames_if_too_short (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 61, in test_filters_whole_email_usernames_if_too_short
    self.assertEqual('[FILTERED]@example.com', self.partially_filter_email_usernames('me@example.com'))
AssertionError: '[FILTERED]@example.com' != 'me@[FILTERED]@example.com'
- [FILTERED]@example.com
+ me@[FILTERED]@example.com
? +++


======================================================================
FAIL: test_obfuscates_more_complicated_emails (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-17j1yn5/test.py", line 37, in test_obfuscates_more_complicated_emails
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[EMAIL]' != 'larodi@x.com'
- [EMAIL]
+ larodi@x.com


----------------------------------------------------------------------
Ran 39 tests in 0.527s

FAILED (failures=6, errors=27)

История (1 версия и 1 коментар)

Антон обнови решението на 22.04.2014 22:46 (преди над 10 години)

+import re
+import datetime
+import time
+
+MAIL_PATTERN = "[a-zA-Z0-9][\w\+\.\-]{1,200}"
+DOMAIN_PATTERN = "([a-zA-Z0-9][a-zA-Z0-9\-]{1,61}[a-zA-Z0-9]\.)+"
+TLD_PATTERN = "([a-zA-Z]{2,3})(\.[a-zA-Z]{2,3})?"
+PHONE_PREFIX_PATTERN = "(0|00|\+)[1-9]\d{0,2}"
+PHONE_MAIN_PATTERN = "(\d[ \-\(\)]{0,2}){6,10}\d"
+
+
+class PrivacyFilter():
+ def __init__(self, text):
+ self.__text_to_be_filtered = text
+ self.preserve_phone_country_code = False
+ self.preserve_email_hostname = False
+ self.partially_preserve_email_username = False
+
+ def __replace_mail_partially(self, match_text):
+ whole_mail = match_text.group()
+ username = re.match(MAIL_PATTERN+'@', whole_mail).group()
+ return re.sub(username, username[0:3]+"[FILTERED]@", whole_mail)
+
+ def __replace_whole_username(self, match_text):
+ return re.sub(MAIL_PATTERN+'@', "[FILTERED]@", match_text.group())
+
+ def __replace_phone_main_part(self, phone):
+ prefix = re.match(PHONE_PREFIX_PATTERN, phone.group()).group()
+ return prefix+' [FILTERED]'
+
+ def filtered(self):
+ replaced = self.__text_to_be_filtered[:]
+ mail = re.compile(MAIL_PATTERN + '@' + DOMAIN_PATTERN + TLD_PATTERN)
+ phone = re.compile(PHONE_PREFIX_PATTERN + PHONE_MAIN_PATTERN)
+
+ email_matches = re.findall(mail, replaced)
+ if email_matches:
+ if self.partially_preserve_email_username:
+ replaced = re.sub(mail, self.__replace_mail_partially, replaced)
+ elif self.preserve_email_hostname:
+ replaced = re.sub(mail, self.__replace_whole_username, replaced)
+ else:
+ replaced = re.sub(mail, "[EMAIL]", replaced)
+
+ phone_matches = re.findall(phone, replaced)
+ if phone_matches:
+ if self.preserve_phone_country_code:
+ replaced = re.sub(phone, self.__replace_phone_main_part, replaced)
+ else:
+ replaced = re.sub(phone, "[PHONE]", replaced)
+
+ return replaced
+
+
+
+class Validations:
+ @classmethod
+ def is_email(cls, mail):
+ mail_pattern = re.compile(MAIL_PATTERN)
+ splitted = re.split("@", mail)
+
+ if len(splitted) > 2:
+ return False
+
+ return (mail_pattern.fullmatch(splitted[0]) is not None
+ and cls.is_hostname(splitted[1]))
+
+ @classmethod
+ def is_phone(cls, phone):
+ phone_regex = re.compile(PHONE_PREFIX_PATTERN + PHONE_MAIN_PATTERN)
+ return re.fullmatch(phone_regex, phone) is not None
+
+ @classmethod
+ def is_hostname(cls, hostname):
+ TLD = TLD_PATTERN
+ domain = DOMAIN_PATTERN
+ return re.fullmatch(domain+TLD, hostname) is not None
+
+ @classmethod
+ def is_ip_address(cls, ip):
+ pattern = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
+ if pattern.fullmatch(ip) is None:
+ return False
+
+ split_ip = re.split('\.', ip)
+
+ for number in split_ip:
+ number = int(number)
+ if number > 255 or number < 0:
+ return False
+ return True
+
+ @classmethod
+ def is_number(cls, value):
+ pattern = re.compile("-?(0|[1-9]\d*)(\.\d+)?")
+ return pattern.fullmatch(value) is not None
+ return False
+
+ @classmethod
+ def is_integer(cls, value):
+ pattern = re.compile("-?(0|[1-9]\d*)")
+ return pattern.fullmatch(value) is not None
+
+ @classmethod
+ def is_date(cls, date_to_check):
+ date_pattern = re.compile("\d{4}-\d{2}-\d{2}")
+ if date_pattern.fullmatch(date_to_check) is None:
+ return False
+
+ try:
+ datetime.datetime.strptime(date_to_check,"%Y-%m-%d")
+ except:
+ return False
+
+ return True
+
+ @classmethod
+ def is_time(cls, time_to_check):
+ time_pattern = re.compile("\d{2}:\d{2}:\d{2}")
+ if time_pattern.fullmatch(time_to_check) is None:
+ return False
+
+ try:
+ time.strptime(time_to_check,"%H:%M:%S")
+ except:
+ return False
+
+ return True
+
+ @classmethod
+ def is_datetime(cls, date_time):
+ delimiter = re.compile("[ ]+|T+")
+ splitted = delimiter.split(date_time)
+ return cls.is_date(splitted[0]) and cls.is_time(splitted[1])