python - 为什么在使用 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()
解决方案
我找到了一种方法来做到这一点,你不需要写很多行,就像你尝试过的那样
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!
然后这个程序会将电子邮件和密码复制到剪贴板
推荐阅读
- modelica - 扩展注释 __Dymola_Commands
- css - 将 webiste 部署到 Github 页面后,CSS 未在本地应用
- python - 用户图像管理页面
- html - 使用 Django 和 MySQL 将数组转换为字符串
- c++ - 自动推断模板类型(带 lambda)
- objective-c - 如何扫描 NSData 以查找可识别的图像、文本、pdf 等
- flutter - Cloud Firestore 子集合颤振应用的模型类
- javascript - React - 如何将我的邀请属性设置为 id 2 的 false
- command-line - 保留文件 grep 中具有多个匹配项的行
- r - 为什么 R 认为我的所有行都以“e”结尾?