我正在尝试处理大量的txt文件,这些文件本身就是我想要处理的实际文件的容器。txt文件有sgml标记,这些标记为我正在处理的各个文件设置边界。有时,所包含的文件是经过超编码的二进制文件。我已经解决了解码uuencoded文件的问题,但当我仔细考虑我的解决方案时,我发现它还不够通用。就是我一直在用
if '\nbegin 644 ' in document['document']测试文件是否经过uuencoded。我做了一些搜索,对644的含义(文件权限)有一个模糊的理解,然后找到了其他uuencoded文件的例子,可能有
if '\nbegin 642 ' in document['document']或者甚至是其他一些替代方案。因此,我的问题是如何确保捕获/识别所有具有uuencoded文件的子容器。
一种解决方案是测试每个子容器:
uudecode=codecs.getdecoder("uu")
for document in documents:
try:
decoded_document,m=uudecode(document)
except ValueError:
decoded_document=''
if len(decoded_document)==0
more stuff这并不可怕,cpu周期很便宜,但我将处理大约800万个文档。
因此,有没有一种更健壮的方法来识别特定字符串是否是or编码的结果?
发布于 2011-01-12 05:39:40
Wikipedia says表示每个uuencoded文件都以此行开头
begin <perm> <name>因此,与正则表达式^begin [0-7]{3} (.*)$匹配的行可能足够可靠地表示开头。
发布于 2011-01-12 05:35:44
两种方式:
(1)在基于Unix的系统上,您可以强健地使用file命令。
http://unixhelp.ed.ac.uk/CGI/man-cgi?file
$ file foo
foo: uuencoded or xxencoded text(2)我还发现了以下(未经测试的) Python代码,它们看起来可以做您想做的事情(在http://ubuntuforums.org/archive/index.php/t-1304548.html上)。
#!/usr/bin/env python
import magic
import sys
filename=sys.argv[1]
ms = magic.open(magic.MAGIC_NONE)
ms.load()
ftype = ms.file(filename)
print ftype
ms.close()https://stackoverflow.com/questions/4662903
复制相似问题