为什么这个代码不起作用?Python

2024-05-14 16:11:27 发布

您现在位置:Python中文网/ 问答频道 /正文

当剪贴板中的文本没有电子邮件地址或电话号码时,即当预期结果为“找不到”时,代码工作正常 在另一种情况下,它是不起作用的。它显示出错误- AttributeError:“str”对象没有属性“matches”

#! python3
# contactDetails.py - Finds email and phone number from a page

import pyperclip, re

phoneRegex = re.compile(r'(\+\d{2}-\d{10})')     # Phone Number Regex
# 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)

text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
    phoneNum=phoneRegex.findall(text)
    matches.append(phoneNum)
for groups in emailRegex.findall(text):
    matches.append(groups[0])

if len(matches) >0:
    pyperclip.copy('\n'.matches)
    print('Copied to Clipboard:')
    print('\n'.join(matches))
else:
    print('Nothing Found')

Tags: textreemailregexgroupsprintmatchescompile
1条回答
网友
1楼 · 发布于 2024-05-14 16:11:27

正如Wiktor Stribiżew在评论中提到的,问题就在这一行

    pyperclip.copy('\n'.matches)

尤其是在这里

'\n'.matches

第一项'\n'是字符串对象,没有可以调用的matches属性。你要做的是做一个。连接,就像你在两行之后做的那样

    pyperclip.copy('\n'.join(matches))

相关问题 更多 >

    热门问题