Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使程序访问任何类型的文件?_Python_Python 3.x - Fatal编程技术网

Python 如何使程序访问任何类型的文件?

Python 如何使程序访问任何类型的文件?,python,python-3.x,Python,Python 3.x,我正在尝试创建一个通用的电子邮件提取器。我参加了一个项目,如下所示: from optparse import OptionParser import os.path import re regex = re.compile(("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`" "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-

我正在尝试创建一个通用的电子邮件提取器。我参加了一个项目,如下所示:

from optparse import OptionParser
import os.path
import re

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)
        else:
            print ('"{}" is not a file.'.format(arg))
            parser.print_usage()
我运行了这个程序,它在
.txt
.csv
扩展文件中运行良好

但问题是,我用来输入这个程序的文件夹也有
.xsls
.doc
.docx
.mdb
.pdf
和其他扩展文件,其中也有电子邮件。我不明白如何修改我的程序来访问这些或任何类型的扩展文件,并从中提取电子邮件


请告诉我如何解决问题的建议。

您应该打开带有“rb”标志的文件

with open(filename, 'rb') as f:

请注意,doc,pdf。。。不是文本文件,因此对于每种类型,您都需要特殊的解析器来解析内容

许多文件(例如
xlsx
docx
)都是压缩的。其他文件(如
doc
mdb
)采用专有格式。您不能只在原始内容上运行正则表达式,然后期望能够找到电子邮件地址。您提到的格式是二进制的,它们不是设计为以文本形式读取的,不能作为文本处理。您可以天真地在假设它们在原位显示为纯文本的情况下扫描它们以查找可识别的字符串,但这无法可靠地工作。例如,docx是压缩的。正确的方法是使用与所讨论的文件类型相适应的解析器。因此,如果不使用解析器读取文件,就没有办法。即使是二进制文件,如果我读取文件,那么是否有可能从文件中提取电子邮件?根据定义,这种算法可以破坏任何/所有加密。@JafferWilson只需在记事本中打开一个.docx/.pdf文件,就可以查看需要处理的文本,如果没有解析器或其他理解底层文件格式的代码,这是不可能的。Windows使用自定义IFilter提供程序进行搜索索引,您可以看到是否有可以使用的API,尽管我无法想象有一个适用于mdb的API。(我使用Agent Ransack进行搜索,它使用IFilter&understands regex标准)使用
rb
我能从任何文件中提取电子邮件吗?不,但在python3中,当打开没有“b”标志的二进制文件时,你会得到
UnicodeDecodeError
你认为你能回答我的问题吗?请你详细说明在我的情况下这对我有什么帮助。正如我所说,我正在尝试从任何类型的文件创建一个电子邮件提取器。