Python действительные номера телефонов - PullRequest
0 голосов
/ 26 сентября 2018

Так что я пытаюсь прочитать телефонные номера из файла, но я не могу заставить его обрабатывать номера, если я добавляю дополнительные цифры в конец. Пример: (123) 456-7890 хорошо, но (123) 456-7890123 также проходит.Как я могу проверить дополнительные номера в конце.

import re # Import Real Expressions

def isValid(s):

    Filter1 = re.compile("[0-9]{3}\-[0-9]{3}\-[0-9]{4}") #Test for format xxx-xxx-xxxx
    return Filter1.match(s) #return true if matches format

def isValid2(s):
    Filter2 = re.compile("\([0-9]{3}\) [0-9]{3}\-[0-9]{4}") #Test for format (xxx) xxx-xxxx
    return Filter2.match(s)# return true if matches format

def findValidPhone():
    filename = "input1.txt" #delcare filename
    with open(filename,"r") as inFile: #openfile
        for line in inFile: #for all the lines in the file
            s = line # store the line as a variable
            # print(s)
            if ( isValid(s)): #run tests using function isValid if true print number
                print(s)
            elif(isValid2(s)): #run test using function isValid2 if true print number
                print(s)
            else: # print invalid number if an invalid number is found in the file
                print("Invalid Number")
inFile.close() #close the file
findValidPhone() #function call

1 Ответ

0 голосов
/ 26 сентября 2018

Вы можете использовать библиотеку phonenumbers для проверки наличия действительного номера телефона.Установите его с помощью pip install phonenumbers.

. Вы можете анализировать отдельные числовые строки и проверять их на правильность:

>>> import phonenumbers
>>> print(phonenumbers.parse("(541) 754-3010", "US"))
Country Code: 1 National Number: 5417543010
>>> phonenumbers.is_valid_number(phonenumbers.parse("(541) 754-3010", "US"))
True

Это сделает гораздо больше проверок, чем ваше регулярное выражение, поскольку, очевидно, ни одно из вашихПримеры: действительный номер телефона в США:

>>> phonenumbers.is_valid_number(phonenumbers.parse("(123) 456-7890123", "US"))
False
>>> phonenumbers.is_valid_number(phonenumbers.parse("(123) 456-7890", "US"))
False

Извлечение чисел из большего текстового блока:

>>> text = '''So im trying to read phone numbers from a file but
... i cant get it to handle numbers if I add extra numbers to the
... end EX: (123) 456-7890 is good but (123) 456-7890123 also goes
... through. How can I check for extra numbers at the end.
... Also we can try (541) 754-3010 as a possible number.
... '''
>>> for match in phonenumbers.PhoneNumberMatcher(text, "US"):
...    print(match.number)
...
Country Code: 1 National Number: 5417543010
>>>
>>> for match in phonenumbers.PhoneNumberMatcher(text, "US"):
...    print(phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL))
...    print(phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.NATIONAL))
...
+1 541-754-3010
(541) 754-3010

Подробнее об этой библиотеке см. https://github.com/daviddrysdale/python-phonenumbers.

...