使用python读取warc文件



我想读取warc文件,我根据这个页面编写了以下代码,但没有打印任何东西!!

>>import warc
>>f = warc.open("01.warc.gz")
>>for record in f:
    print record['WARC-Target-URI'], record['Content-Length']

然而,当我写下面的命令时,我得到了结果

>>print f
<warc.warc.WARCFile instance at 0x0000000002C7DE88>

请注意,我的warc文件是Clueweb09数据集中的一个文件。我提到它是因为这个页面

我和你有同样的问题。

经过对模块的一些研究,我找到了一个解决方案。

尝试使用record.payload.read(),这里是完整的示例:

import warc
f = warc.open("01.warc.gz")
for record in f:
  print record.payload.read()

同样,我可以说你不仅可以读取warc文件,也可以读取wet文件。小窍门是将其重命名为包含.warc

的名称。

亲切的问候

首先,WARC,即Web ARChive,是一种网页的存档格式。读取warc文件有点棘手,因为它包含一些特殊的头文件。假设您的warc文件是这种格式。

您可以使用以下代码来加载、解析并返回包含元数据和内容的每个记录的字典。

def read_header(file_handler):
    header = {}
    line = next(file_handler)
    while line != 'n':
        key, value = line.split(': ', 1)
        header[key] = value.rstrip()
        line = next(file_handler)
    return header

def warc_records(path):
    with open(path) as fh:
        while True:
            line = next(fh)
            if line == 'WARC/1.0n':
                output = read_header(fh)
                if 'WARC-Refers-To' not in output:
                    continue
                output["Content"] = next(fh)
                yield output

你可以按下列方式访问字典:

records = warc_records("<some path>')
>>> next_record = next(records)
>>> sorted(next_record.keys())
['Content', 'Content-Length', 'Content-Type', 'WARC-Block-Digest', 'WARC-Date', 'WARC-Record-ID', 'WARC-Refers-To', 'WARC-Target-URI', 'WARC-Type', 'WARC-Warcinfo-ID']
>>> next_record['WARC-Date']
'2013-06-20T00:32:15Z'
>>> next_record['WARC-Target-URI']
'http://09231204.tumblr.com/post/44534196170/high-res-new-photos-of-the-cast-of-neilhimself'
>>> next_record['Content'][:30]
'Side Effects high res. New pho'

最新更新