Exemple #1
0
    def get_phone_number_object(self, data_string):
        """
        Takes the data_string and tries to parse a phone number out of it

        :param data_string: data that might be a phone number
        :type data_string: str
        :return: phone number data if it's a phone number
        :rtype: dict
        """
        try:
            check_region = (data_string[0] == "+")

            # First pass to see if it's a valid number
            num_obj = phonenumberutil.parse(
                data_string,
                _check_region=check_region
            )

            num_desc = geocoder.description_for_valid_number(
                num_obj, "en"
            ).strip()

        except NumberParseException:
            # If we can't parse it out, it's not a valid number
            return False

        # if we weren't able to check the region, and we didn't get a
        # description we want to modify the data and give it another go
        # with a country code added
        if not check_region and not num_desc:
            prefix = None
            if len(self.digits) == 11 and data_string[0] == "1":
                prefix = "+"
            elif len(self.digits) == 10 \
                    and (data_string[0].isdigit() or
                         data_string[0] in string.punctuation):
                prefix = "+1"

            if prefix:
                try:
                    # Second pass to see if we can get an actual
                    # geocode out of it using a hammer
                    second_pass = phonenumberutil.parse(prefix + data_string)
                    num_desc = geocoder.description_for_valid_number(
                        second_pass, "en"
                    ).strip()
                    if num_desc:
                        num_obj = second_pass
                        # confidence hit because we had to
                        # modify the data to get a result
                        self.confidence -= 5
                except (NumberParseException, Exception):
                    pass

        # Attempting to get a valid region
        num_region = phonenumberutil.region_code_for_number(num_obj)

        # This is the compiled phone number data that
        # we will use for the confidence decision
        return self.build_phone_number_dict(num_obj, num_desc, num_region)
Exemple #2
0
    def get_phone_number_object(self, data_string):
        """Takes the data_string and tries to parse a phone number out of it"""

        try:
            check_region = (data_string[0] == "+")

            # First pass to see if it's a valid number
            num_obj = phonenumberutil.parse(
                data_string,
                _check_region=check_region
            )

            num_desc = geocoder.description_for_valid_number(
                num_obj, "en"
            ).strip()

        except NumberParseException:
            # If we can't parse it out, it's not a valid number
            return False

        # if we weren't able to check the region, and we didn't get a
        # description we want to modify the data and give it another go
        # with a country code added
        if not check_region and not num_desc:
            prefix = None
            if len(self.digits) == 11 and data_string[0] == "1":
                prefix = "+"
            elif len(self.digits) == 10 \
                    and (data_string[0].isdigit() or
                         data_string[0] in string.punctuation):
                prefix = "+1"

            if prefix:
                try:
                    # Second pass to see if we can get an actual
                    # geocode out of it using a hammer
                    second_pass = phonenumberutil.parse(prefix + data_string)
                    num_desc = geocoder.description_for_valid_number(
                        second_pass, "en"
                    ).strip()
                    if num_desc:
                        num_obj = second_pass
                        # confidence hit because we had to
                        # modify the data to get a result
                        self.confidence -= 5
                except (NumberParseException, Exception):
                    pass

        # Attempting to get a valid region
        num_region = phonenumberutil.region_code_for_number(num_obj)

        # This is the compiled phone number data that
        # we will use for the confidence decision
        return self.build_phone_number_dict(num_obj, num_desc, num_region)
Exemple #3
0
 def testGetDescriptionForArgentinianMobileNumber(self):
     self.assertEqual("La Plata", description_for_number(AR_MOBILE_NUMBER, _ENGLISH))
     # Python version extra test
     # Put an invalid number after the mobile token ("9") and lie about
     # this being a valid number
     arInvalidMobileNumber = PhoneNumber(country_code=54, national_number=91)
     self.assertEqual("Argentina", description_for_valid_number(arInvalidMobileNumber, _ENGLISH))
 def testGetDescriptionForArgentinianMobileNumber(self):
     self.assertEqual("La Plata", description_for_number(AR_MOBILE_NUMBER, _ENGLISH))
     # Python version extra test
     # Put an invalid number after the mobile token ("9") and lie about
     # this being a valid number
     arInvalidMobileNumber = PhoneNumber(country_code=54, national_number=91)
     self.assertEqual("Argentina", description_for_valid_number(arInvalidMobileNumber, _ENGLISH))
def validate_phone(form, field):
    """
     Validate the form's phone number is valid for the form's country state code.
     1. Extract the state name from the form's phone number.
     2. Look up the state name from the 'usa_states' list, with the form's country state code.
     3. If both state names match, then pass, else throw a validation error.
    """
    try:
        input_phone_number = field.data
        input_state_code = form.state.data
        parsed_phone_number = phonenumbers.parse(input_phone_number, 'US')

        if not phonenumbers.is_valid_number(parsed_phone_number):
            raise ValidationError('invalid phone number.')

        phone_number_state_name = geocoder.description_for_valid_number(
            parsed_phone_number, 'en')

        # Look up the state name from the 'usa_states' list, with the form's country state code.
        matching_state = next((value for index, value in enumerate(usa_states)
                               if value[0] == input_state_code), None)

        if not matching_state[1] == phone_number_state_name:
            raise ValidationError(
                'number\'s area code does not match the selected state')

    except NumberParseException as e:
        raise ValidationError('invalid phone number.')
Exemple #6
0
    def testCoverage(self):
        # Python version extra tests
        invalid_number = PhoneNumber(country_code=210, national_number=123456)
        self.assertEqual("", country_name_for_number(invalid_number, "en"))
        # Ensure we exercise all public entrypoints directly
        self.assertEqual("CA", _prefix_description_for_number(TEST_GEOCODE_DATA, TEST_GEOCODE_LONGEST_PREFIX, US_NUMBER1, "en"))
        self.assertEqual("CA", description_for_valid_number(US_NUMBER1, "en"))
        self.assertEqual("", description_for_valid_number(US_INVALID_NUMBER, "en"))
        # Add in some script and region specific fictional names
        TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA"),
                                        "en_GB": u("Mountain View California"),
                                        "en_US": u("Mountain View, Sunny California"),
                                        "en_Xyzz_US": u("MTV - xyzz"),
                                        "en_Latn": u("MountainView")}
        # The following test might one day return "Mountain View California"
        self.assertEqual("United States",
                         description_for_number(US_NUMBER2, _ENGLISH, region="GB"))
        self.assertEqual("Mountain View, Sunny California",
                         description_for_number(US_NUMBER2, _ENGLISH, region="US"))
        self.assertEqual("MountainView",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn"))
        self.assertEqual("United States",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB"))
        self.assertEqual("MTV - xyzz",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Xyzz", region="US"))
        self.assertEqual("Mountain View, Sunny California",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Zazz", region="US"))
        # Get a different result when there is a script-specific variant
        self.assertEqual("MountainView",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US"))
        TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA")}

        # Test the locale mapping
        TEST_GEOCODE_DATA['8862'] = {'zh': u("Chinese"), 'zh_Hant': u("Hant-specific")}
        tw_number = FrozenPhoneNumber(country_code=886, national_number=221234567)
        self.assertEqual("Hant-specific",
                         description_for_number(tw_number, "zh", region="TW"))
        del TEST_GEOCODE_DATA['8862']
    def testCoverage(self):
        # Python version extra tests
        invalid_number = PhoneNumber(country_code=210, national_number=123456)
        self.assertEqual("", country_name_for_number(invalid_number, "en"))
        # Ensure we exercise all public entrypoints directly
        self.assertEqual("CA", _prefix_description_for_number(TEST_GEOCODE_DATA, TEST_GEOCODE_LONGEST_PREFIX, US_NUMBER1, "en"))
        self.assertEqual("CA", description_for_valid_number(US_NUMBER1, "en"))
        self.assertEqual("", description_for_valid_number(US_INVALID_NUMBER, "en"))
        # Add in some script and region specific fictional names
        TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA"),
                                        "en_GB": u("Mountain View California"),
                                        "en_US": u("Mountain View, Sunny California"),
                                        "en_Xyzz_US": u("MTV - xyzz"),
                                        "en_Latn": u("MountainView")}
        # The following test might one day return "Mountain View California"
        self.assertEqual("United States",
                         description_for_number(US_NUMBER2, _ENGLISH, region="GB"))
        self.assertEqual("Mountain View, Sunny California",
                         description_for_number(US_NUMBER2, _ENGLISH, region="US"))
        self.assertEqual("MountainView",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn"))
        self.assertEqual("United States",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB"))
        self.assertEqual("MTV - xyzz",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Xyzz", region="US"))
        self.assertEqual("Mountain View, Sunny California",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Zazz", region="US"))
        # Get a different result when there is a script-specific variant
        self.assertEqual("MountainView",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US"))
        TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA")}

        # Test the locale mapping
        TEST_GEOCODE_DATA['8868'] = {'zh': u("Chinese"), 'zh_Hant': u("Hant-specific")}
        tw_number = FrozenPhoneNumber(country_code=886, national_number=810080123)
        self.assertEqual("Hant-specific",
                         description_for_number(tw_number, "zh", region="TW"))
        del TEST_GEOCODE_DATA['8868']
# !pip3 install phonenumbers
import phonenumbers
from phonenumbers import carrier
from phonenumbers import geocoder
phone_number = phonenumbers.parse(
    input('Enter phone numbers with coutry code: '))
# this will print the country name
print(geocoder.description_for_valid_number(phone_number, 'en'))
#this will print the  service provider name
print(carrier.name_for_valid_number(phone_number, 'en'))