我有一个项目,我给了一个文件,我需要从文件中提取字符串。基本上想到在Linux中的“字符串”命令,但我在python中这样做。下一个条件是文件以流(例如字符串)的形式提供给我,所以使用其中一个子进程函数运行字符串的明显答案也不是一个选项。从Python中的二进制文件中提取字符串
我写了这个代码:
def isStringChar(ch):
if ord(ch) >= ord('a') and ord(ch) <= ord('z'): return True
if ord(ch) >= ord('A') and ord(ch) <= ord('Z'): return True
if ord(ch) >= ord('0') and ord(ch) <= ord('9'): return True
if ch in ['/', '-', ':', '.', ',', '_', '$', '%', '\'', '(', ')', '[', ']', '<', '>', ' ']: return True
# default out
return False
def process(stream):
dwStreamLen = len(stream)
if dwStreamLen < 4: return None
dwIndex = 0;
strString = ''
for ch in stream:
if isStringChar(ch) == False:
if len(strString) > 4:
#print strString
strString = ''
else:
strString += ch
这种技术上的工作,但WAY缓慢。例如,我能够在500Meg可执行文件上使用strings命令,并在不到1秒的时间内生成了价值300K的字符串。我通过上面的代码运行了相同的文件,花了16分钟。
在那里有一个库,可以让我在没有python延迟的情况下执行此操作吗?
谢谢!
如果您可以阅读C [GNU字符串的源代码](http://sourceware.org /cgi-bin/cvsweb.cgi/src/binutils/strings.c?rev=1.48&content-type=text/x-cvsweb-markup&cvsroot=src)可能会有帮助。它只有几百行,所以没那么糟糕。 –