在文本中查找有效的电话号码,找不到号码

问题描述 投票:0回答:2

我正在编写一个程序来检查字符串以确保它是否是有效的电话号码(例如415-555-1011)

def isPhoneNumber(text):
    if len(text)!= 12:
        return False
    for i in range(0,3):
        if not text[i].isdecimal():
            return False
        if text[3]!='-':
            return False
    for i in range(4,7):
        if text[i].isdecimal():
            return False
        if text[7]!='-':
            return False
    for i in range(8,12):
        if not text[i].decimal():
            return False
        return True

message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
    chunk = message[i:i+12]
    if isPhoneNumber(chunk):
        print('Phone number found: ' + chunk)

print('Done')

我应该得到以下输出

Phone number found: 415-555-1011
Phone number found: 415-555-9999
Done 

但我只是得到了

Done

我没有得到前两行

python python-3.x
2个回答
1
投票

您在第二个循环中缺少not

for i in range(4,7):
    if text[i].isdecimal():
        return False

在你的上一个循环中,你使用text[i].decimal()而不是text[i].isdecimal()

当任何这些字符是数字时,返回False。你想用:

for i in range(4,7):
    if not text[i].isdecimal():
        return False

您还要在每个循环中的每个迭代的下一个位置测试一个破折号字符(您只需要在这些循环之后进行测试),并且最后的return True也需要移出该循环(您只测试对于位置8)的数字。

你不需要测试每个角色;你可以使用一个切片:

def isPhoneNumber(text):
    if len(text) != 12:
        return False
    if not text[:3].isdecimal():
        return False
    if text[3] != '-':
        return False
    if not text[4:7].isdecimal():
        return False
    if text[7] != '-':
        return False
    if not text[8:12].isdecimal():
        return False
    return True

您可以使用正则表达式简化所有这些:

import re

phone_numbers = re.compile(r'\b\d{3}-\d{3}-\d{4}\b')

for number in phone_numbers.findall(message):
    print('Phone number found:', number)

请注意,此模式实际上禁止电话号码成为更长号码的一部分(您的代码会在0014213012345-444-123244214324中找到电话号码;所需要的只是一个3位数字的中间组,用短划线包围,3位数前缀和4位数字后缀)。 \b模式要求在匹配的电话号码之前和之后存在非单词字符(除字母,数字或下划线之外的任何字符)。


0
投票

嗨你可以试试这个逻辑: -

def msg_phone():
    message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
    number=re.findall('[0-9]{3}-[0-9]{3}-[0-9]{4}',message)
    for i in number:
        print('Phone number found:',i)
    print('Done')

代码长度少得多,复杂性也是如此。

© www.soinside.com 2019 - 2024. All rights reserved.