Monday, 20 February 2017

python script to find out a mobile number from a file

Say we have a file named file.txt , now we will try to find out all the mobile nos that is written in that file .


file.txt has the bellow contents .

Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.


Now we will write a script that will find out all the phone nos that is present in that file .


First Method :

def isPhoneNo(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 not text[i].isdecimal():
                        return False

        if text[7] !='-':
                return False

        for i in range(8,12):
                if not text[i].isdecimal():
                        return False
        return True

file=open('file.txt','r')
file1=file.read()

for i in range(len(file1)):
        chunk=file1[i:i+12]
        if isPhoneNo(chunk):
                print('Phone no is:'+chunk )




Second Method:

import re

file=open('file','r')
file1=file.read()
print(re.compile(r'\d\d\d-\d\d\d-\d\d\d\d').findall(file1))


You will get the following output: (Here both the script are in the same file.)






Add me in facebook HERE


No comments:

Post a Comment

Popular Posts