不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2022-02-19 11:52:33  修改时间:2024-03-28 12:47:15  分类:数据采集/桌面自动化  编辑
# python 3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard


# pyperclip 模块有 copy()和 paste()函数, 可以向计算机的剪贴板发送文本, 或从它接收文本
# re模块 正则表达式是对字符串进行操作,正则表达式是对字符串进行模糊匹配,提取自己需要的字符串部分
import pyperclip, re

# 0. 为电话号码创建一个正则表达式

phoneRegex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?              # area code 区号三个数字(\d{3}),多个部分(|),括号中的三个数字(\(\d{3}\)) 选择其中一个:()?
    (\s|-|\.)?                      # separator 电话号码分割字符可以是空格:\s,短横:-,句点:\.,管道连接:|
    (\d{3})                         # first 3 digits 3个数字(\d{3})
    (\s|-|\.)                       # separator 分隔符
    (\d{4})                         #last 4 digits 4个数字
    (\s*(ext|x|ext.)\s*(\d{2, 5}))? #extension 可选(?)分机号, 任意数目空格(\s*), ext或x或ext.(ext|x|ext.),2或者5个数字\d{2, 5})
    )''', re.VERBOSE)

# TODO: create email regex
# 1. 为E-mail地址创建一个正则表达式
emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+               # username 用户名部分是一个或多个字符,字符可包括:小写和大写字母、数字、句点、下划线、百分号、加号或短横
    @                               # @ symbol 域名和用户名用@符号分割
    [a-zA-Z0-9.-]+                  # domain name 域名允许的字符分类少一点,只允许字母、数字、句点和短横[a-zA-Z0-9.-]
    (\.[a-zA-Z]{2,4})               # dot-something 最后是“dot-com”部分,实际上可以是“dot—anything”。有2-4个字符
    )''', re.VERBOSE)



# TODO: find matches in clipboard text
# 2. 在剪切板文本中找到所有匹配
text = str(pyperclip.paste())
matches = []                                                 # 将所有匹配保存在list中
for groups in phoneRegex.findall(text):
    phoneNum = '-'.join([groups[1], groups[3], groups[5]])   # 字符串,由匹配的文本的分组1、3、5和8构成,这些分组分别为区号,前3个数字,后4个数字和分机号  
    if groups[8] != ' ':
        phoneNum += ' x' + groups[8]
    matches.append(phoneNum)
for groups in emailRegex.findall(text):                      # 将每次的分组0添加到list中
    matches.append(groups[0])



# TODO: copy results to the clipboard
# 3. 所有匹配连接成一个字符串,复制到剪贴板
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 .')
 

 

 

参考:https://blog.csdn.net/weixin_45837461/article/details/107015882