首页 > 解决方案 > 为什么在使用 pyperclip 时只复制一条语句

问题描述

我尝试在文本文件中创建一个查找电子邮件地址,它工作得很好。使用 pyperclip 后,我只能复制最后一个电子邮件地址,但我想将所有电子邮件复制到剪贴板。我该怎么做。我也想如果你有更好的方法来做这件事,请尝试另一种方法,请让我知道。顺便说一句,我有另一个文本文件,其中包含带有电子邮件的文本文件。我使用这个 gitlist 来制作这个 python 程序gitlist 链接

from optparse 
import OptionParser

import os.path

import re

import pyperclip


regex = re.compile(("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"

                    "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"

                    "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))


def file_to_str(filename):

    """Returns the contents of filename as a string."""

    with open(filename) as f:

        return f.read().lower() # Case is lowered to prevent regex mismatches.


def get_emails(s):

    """Returns an iterator of matched emails found in string s."""

    # Removing lines that start with '//' because the regular expression

    # mistakenly matches patterns like 'http://foo@bar.com' as '//foo@bar.com'.

    return (email[0] for email in re.findall(regex, s) if not email[0].startswith('//'))


if __name__ == '__main__':

    parser = OptionParser(usage="Usage: python %prog [FILE]...")

    # No options added yet. Add them here if you ever need them.

    options, args = parser.parse_args()


    if not args:

        parser.print_usage()

        exit(1)


    for arg in args:

        if os.path.isfile(arg):

            for email in get_emails(file_to_str(arg)):

                print(email)

                pyperclip.copy(email)

        else:

            print('"{}" is not a file.'.format(arg))

            parser.print_usage()

标签: pythonpython-3.x

解决方案


我找到了一种方法来做到这一点,你不需要写很多行,就像你尝试过的那样

with open(r"text.txt", "r") as txt_reader:
found_email = "Not Found"

for line in txt_reader:
    if "email" in line.lower():
        #Breaks line into a list of words seperated by ':' Choses the 2nd 
     word and removes blank spaces        
        found_email = line.split(":")[1].strip()

print(found_email)

例如,如果您的 test.txt 文件是这样的

Email: susantha@gmail.com

Password: pas5w0rd!

然后这个程序会将电子邮件和密码复制到剪贴板


推荐阅读