python 电话号码和Email提取

2022-08-01,,,

【小练习】python 电话号码和Email提取

使用正则表达式、pyperclip

1. 电话号码的正则表达式:
电话号码的格式类似 415-555-4242,最前面三位区号可能有括号,区号可能有也可能没有,中间的分隔可能是-,空格,句点。

(\d{3}|\(\d{3}\))?      # 区号
(-|\s|\.)?              # 区号后的分隔符

2. Email的正则表达式:
用户名部分可能是数字,字母,句点,_,%,+,-。用@分隔用户名和域名。

[a-zA-Z0-9._%+-]+       # 用户名

[a-zA-Z0-9.-]+          # 域名

3. 在剪切板文本中找到匹配:

pyperclip

4. 所有匹配连接成字符串复制到剪切板:

join

完整程序如下:

#! pyhon3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.

import pyperclip, re

phoneRegex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?               # area code
    (\s|-|\.)?                       # separator
    (\d{3})                          # first 3 digits
    (\s|-|\.)                        # separator
    (\d{4})                          # last 4 digits
    (\s*(ext|x|ext\.)\s*(\d{2,5}))?  # extension
)''',re.VERBOSE)

# Create email regex.
emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+                # username
    @                                # @ symbol
    [a-zA-Z0-9.-]+                   # domain name
    (\.[a-zA-Z]{2,4})                # dot-something
)''', re.VERBOSE)

# Find matches in clipboard text.
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
    phoneNum = '-'.join([groups[1], groups[3], groups[5]])
    if groups[8] != '':
        phoneNum += ' x' + groups[8]
    matches.append(phoneNum)
for groups in emailRegex.findall(text):
    matches.append(groups[0])

# Copy results to the clipboard.
if len(matches) > 0:
    pyperclip.copy('\n'.join(matches))
    print('Copied to clipboard:')
    print('\n'.join(matches))
else:
    print('No phone numbers or email addresses found.')

5. 运行程序:
运行前需要添加.bat文件,配置环境变量,和口令保管箱方法相同

没有找到电话号码或Email:

找到内容:

本文地址:https://blog.csdn.net/Kev_Zhang/article/details/107385844

《python 电话号码和Email提取.doc》

下载本文的Word格式文档,以方便收藏与打印。