In: Computer Science
PYTHON Exercise 3. Phone Number and Email Address
Extractor
Say you have the boring task of finding every phone number and
email address in a long web page or document. If you manually
scroll through the page, you might end up searching for a long
time. But if you had a program that could search the text in your
clipboard for phone numbers and email addresses, you could simply
press ctrl-A to select all the text, press ctrl-C to copy it to the
clipboard, and then run your program. It could replace the text on
the clipboard with just the phone numbers and email addresses it
finds.
So, your phone and email address extractor will need to do the
following: - Get the text off the clipboard. - Find all phone
numbers and email addresses in the text. - Paste them onto the
clipboard.
Below is a python3 solution that uses "pyperclip" and "regex" modules to solve the above problem. It works on Windows, Linux, and macOS. Comments are provided on every line explaining the code.
#CODE STARTS HERE-----------
import pyperclip #python module to copy/paste from clipboard import re #regex library doc=pyperclip.paste() #copying document from clipboard x=re.findall("([0-9]{3}-[0-9]{3}-[0-9]{4}|\([0-9]{3}\) [0-9]{3}-[0-9]{4})",doc) #regex to find all USA phone numbers. y=re.findall(r"([A-Za-z0-9]+[\s]*\[at\][\s]*[A-Za-z0-9]+|[A-Za-z0-9]+@[A-Za-z0-9]+\.[a-zA-Z]*)", doc) #regex to find all email ids. z="Phone numbers:\n"+"\n". join (a for a in x ) + "\n\nEmail ids:\n"+"\n".join(b for b in y) #adding all phone numbers and emails into a single document pyperclip.copy(z) #pasting the document to clipboard again
#CODE ENDS HERE---------------
Below is a screenshot of the code:
CODE EXECUTION:
STEP 1:
Copying the following document(Ctrl+c):
STEP 2:
Running the python code
STEP 3:
After successful code execution, pasting the clipboard contents(ctrl+v):