所以我正在使用维基百科转储文件。它是一个经过 bzip 压缩的 XML 文件。我可以将所有文件写入目录,但是当我想做分析时,我必须重新读取磁盘上的所有文件。这使我可以随机访问,但速度很慢。我有 ram 将整个 bzipped 文件放入 ram 中。
我可以很好地加载转储文件并读取所有行,但我无法在其中查找,因为它太大了。从表面上看,bz2 库必须读取并捕获偏移量,然后才能将我带到那里(并将其全部解压缩,因为偏移量以解压缩字节为单位)。
不管怎样,我正在尝试 mmap 转储文件(~9.5 gigs)并将其加载到 bzip 中。我显然想之前在 bzip 文件上测试一下。
我想将 mmap 文件映射到 BZ2File,这样我就可以通过它进行查找(以获取特定的、未压缩的字节偏移量),但从看来,如果不解压缩整个 mmap 文件,这是不可能的(这将远远超过 30千兆字节)。
我有什么选择吗?
这是我编写的一些代码来测试。
import bz2
import mmap
lines = '''This is my first line
This is the second
And the third
'''
with open("bz2TestFile", "wb") as f:
f.write(bz2.compress(lines))
with open("bz2TestFile", "rb") as f:
mapped = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
print "Part of MMAPPED"
# This does not work until I hit a minimum length
# due to (I believe) the checksums in the bz2 algorithm
#
for x in range(len(mapped)+2):
line = mapped[0:x]
try:
print x
print bz2.decompress(line)
except:
pass
# I can decompress the entire mmapped file
print ":entire mmap file:"
print bz2.decompress(mapped)
# I can create a bz2File object from the file path
# Is there a way to map the mmap object to this function?
print ":BZ2 File readline:"
bzF = bz2.BZ2File("bz2TestFile")
# Seek to specific offset
bzF.seek(22)
# Read the data
print bzF.readline()
这一切都让我想知道,bz2 文件对象有什么特别之处,允许它在查找后读取一行?它是否必须读取之前的每一行才能从算法中获取校验和才能正确计算?
我找到了答案! James Taylor 编写了几个用于在 BZ2 文件中查找的脚本,他的脚本位于 biopython 模块中。
https://bitbucket.org/james_taylor/bx-python/overview https://bitbucket.org/james_taylor/bx-python/overview
这些工作得很好,尽管它们不允许在 BZ2 文件中查找任意字节偏移量,但他的脚本读出 BZ2 数据块并允许基于块进行查找。
特别是,请参阅bx-python / wiki / IO / SeekingInBzip2Files https://bitbucket.org/james_taylor/bx-python/wiki/IO/SeekingInBzip2Files
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)